#include "yk_form_rk.h"
#include "ui_yk_form_rk.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QHeaderView>
#include <QSqlError>
#include "pub_var.h"
#include <QCompleter>

/*
com_printer_setting 表的使用。
p_type : 打印类别，入出库单。
p_item : 项目名称，
p_top， p_left，p_width，p_height 坐标定义

p_item_type 为 item，（p_top， p_left），（p_width，p_height）为区域左上角坐标和右下角坐标。
或者，p_width = p_height = 0， p_top， p_left为表格行，列值，可通过表格行列推算出对应坐标值。
top, left 为负值表示组合值，百位为起始，个位为终止。

p_item_type 为 base，
    p_item = 页面 ，p_width，p_height 定义页面大小。

    p_item = line_landscape，横线
    p_item = line_portrait，竖线
    （p_top， p_left），（p_width，p_height）为线段起始坐标和终止坐标。
    p_print_item 为以^隔开的步长列表，

p_font_name ： 字体名称
p_font_size ： 字体大小，单位mm
p_position ： 对齐方式 0:左，1:中，2:右,
p_mode ：打印模式：1, p_print_item + 项目内容; 0, 只打印项目内容
p_print_item ：与打印模式相关。
p_item_type ： 项目类型， item 内容项目，base 基础项目

*/

const int MAX_LINES = 8;    //单据最大项目数量

Form_yk_rk::Form_yk_rk(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_yk_rk)
{
    ui->setupUi(this);

    initialFinished = false;

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/yk_rk").toRect();
    this->setGeometry(rct);
    ui->pb_unlock_status_out->setEnabled(false);
    ui->pb_status_unlock_in->setEnabled(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrmt = new QSqlQuery(pub::db_m);
    qrmp = new QSqlQuery(pub::db_m);
    qrot = new QSqlQuery(pub::db_o);

    md = new QSqlQueryModel();
    mdrd = new QSqlQueryModel();
    mdrs = new QSqlQueryModel();
    mdcd = new QSqlQueryModel();
    mdcs = new QSqlQueryModel();
    //mdconf = new QSqlQueryModel();

    sq  = "select dept_name,dept_code from com_department where valid_state = '1'"
          " and dept_type in ('P','PI') order by dept_type,dept_name";//,'N' ,护士站
    qDebug()<<"提取全部库存单位："<<sq;
    store_depts = pub::fillCombo(ui->cbbReceiveDept, sq, -1);                //出库操作的接收库

    sq = "select role_dept from com_privileges WHERE type = 'dept' and code = '" + pub::usr_code + "'";
    qDebug()<<"提取操作员有权限的库存单位："<<sq;
    qrmt->exec(sq);
    ui->cbbStoreDept->clear();

    qDebug()<<store_depts;
    while(qrmt->next())
    {
        QString tmp = qrmt->value(0).toString();

        if(store_depts.indexOf(tmp) > -1)
        {
            ui->cbbStoreDept->addItem(tmp);
        }
    }


    sq = "SELECT CLASS3_NAME, CLASS3_CODE,CLASS3_MEANING_CODE "
         " from COM_PRIV_CLASS3 where mark = '1' and CLASS2_CODE = '0310' order by CLASS3_CODE";
    qDebug()<<"提取入库操作类别："<<sq;
    mode_code_r = pub::fillCombo(ui->cbbMode_r, sq, -1, qro);

    sq = "SELECT CLASS3_NAME, CLASS3_CODE,CLASS3_MEANING_CODE "
         " from COM_PRIV_CLASS3 where mark = '1' and CLASS2_CODE = '0320' order by CLASS3_CODE";
    qDebug()<<"提取出库操作类别："<<sq;
    mode_code_c = pub::fillCombo(ui->cbbMode_c, sq, -1, qro);

    //入出库临时表
    sq = "create temporary table if not exists tmp_pha_input (";
    sq += "atinc int auto_increment not null key, ";  //流水编码
    sq += "item_code VARCHAR(12) not null  , ";  //药品编码  unique
    sq += "item_name VARCHAR(100) not null,";          //品名
    sq += "fac_code varchar(10) not null, ";      //生产商代码
    sq += "fac_name varchar(64) not null, ";      //生产商名称
    sq += "specs varchar(50) not null,";               //规格
    sq += "approve_info VARCHAR(20) not null, "; //批准文号
    sq += "pack_qty varchar(10) not null , ";   //包装数量  decimal(10)
    sq += "pack_unit VARCHAR(12) not null , ";   //包装单位
    sq += "drug_type VARCHAR(5) not null , ";   //药品类别，中药，西药
    sq += "drug_quality VARCHAR(5) not null , ";   //药品类别，普药，特药
    sq += "retail_price varchar(20) not null , ";   //零售价格 decimal(12,2)
    sq += "purchase_price varchar(20) not null, ";   //采购价格 decimal(12,2)
    sq += "batch_no varchar(15), ";   //批号
    sq += "manu_date varchar(10), ";   //生产日期
    sq += "valid_date varchar(10), ";   //效期
    sq += "num varchar(10), ";   //出入数量
    sq += "invo_no varchar(25), ";   //发票号
    sq += "invo_date varchar(10), ";   //发票日期
    sq += "memo varchar(255), ";   //备注
    sq += "purchase_cost decimal(12,2) ,";   //购入金额
    sq += "retail_cost decimal(12,2) ,";   //零售金额
    sq += "min_unit varchar(10), ";   //最小单位
    sq += "group_code varchar(6),"; //组
    sq += "out_bill_code varchar(12),"; //出库单号
    sq += "out_serial_code varchar(6),"; //出库单序号
    sq += "out_list_code varchar(16),"; //出库单号
    sq += "input_check_no varchar(15),"; //验收记录流水号
    sq += "med_list_codg varchar(45) ";   //医保码
    sq += ")";

    qDebug()<<"create temporary table :"<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }
    //增加临时表索引
    qrm->exec("alter table tmp_pha_input "
              " add unique index prim_key (item_code,batch_no,group_code )");

    qrm->exec("delete from tmp_pha_input");
    showList();

    ui->tabWidget->setCurrentIndex(0);  //入库    

    //报表使用收款打印机
    QString printerName = setIni.value("sk/printer").toString();

    //配置打印机
    prt= new QPrinter(QPrinter::HighResolution);
    prt->setPrinterName(printerName);

    //发票纸张大小设定
    qrm->exec("select p_width,p_height,p_item from com_printer_setting where "
              " p_item_type = 'base' and p_type = '入出库单' and p_item in('偏移', '页面','单元缩进')");
    double w = 0, h = 0;
    xPos = yPos = 0;

    while(qrm->next())
    {
        QString itm = qrm->value(2).toString() ;

        if( itm == "页面")
        {
            w = qrm->value(0).toDouble();
            h = qrm->value(1).toDouble();
        }else if(itm == "偏移"){
            xPos = qrm->value(0).toDouble();
            yPos = qrm->value(1).toDouble();
        }else if(itm == "单元缩进"){
            margin = qrm->value(0).toDouble();
        }
    }

    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 ;

    prt->setOrientation(QPrinter::Portrait);      //Portrait 纵向, Landscape 横向
    prt->setFullPage(true);
    pnt = new QPainter();

    //单据打印相关
    ui->deBegin->setDate(QDate::currentDate());
    ui->deEnd->setDate(QDate::currentDate());
    md_p_in = new QSqlQueryModel(); //入
    md_p_out = new QSqlQueryModel(); //出
    md_p_brw = new QSqlQueryModel();  //浏览

    //项目维护相关

    sq = "select FAC_NAME, FAC_CODE from PHA_COM_COMPANY where COMPANY_TYPE = '0' and VALID_FLAG = '1' order by FAC_NAME";
    qDebug()<<"提取生产厂家："<<sq;

    QStringList itemList;
    qro->exec(sq);
    while(qro->next())
    {
        itemList << qro->value(0).toString();
        producer_code.append(qro->value(0).toString() + "^" + qro->value(1).toString() + "^");
    }

    initialFinished = true;
}

Form_yk_rk::~Form_yk_rk()
{
    delete ui;
}

void Form_yk_rk::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/yk_rk", QVariant(this->geometry()));
    //delete timer_fac_changed;
    emit destroyW( "yk_rk" );

}

void Form_yk_rk::on_pbExit_clicked()
{
    close();
}

void Form_yk_rk::on_pbSearch_clicked()
{

    search_item(ui->leKey->text().trimmed(),    //检索关键字
                mdrs,                           // sqlmodel
                ui->tvSource_r,                 //显示列表
                ui->cbbMode_r->currentText());                          //入库模式
}

void Form_yk_rk::on_leKey_returnPressed()
{
    on_pbSearch_clicked();
}

void Form_yk_rk::item_selected(const QModelIndex index)
{
    item_detail.clear();
    item_detail.insert("item_name", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs", index.siblingAtColumn(1).data().toString());   //规格
    item_detail.insert("item_name_0", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs_0", index.siblingAtColumn(1).data().toString());   //规格

    item_detail.insert("fac_name", index.siblingAtColumn(2).data().toString());   //生产商
    item_detail.insert("approve_info", index.siblingAtColumn(3).data().toString());   //批准文号, 项目维护的 drug_code
    if(index.siblingAtColumn(4).isValid())
    {
        item_detail.insert("pack_qty", index.siblingAtColumn(4).data().toString());   //包装数量
        item_detail.insert("pack_unit", index.siblingAtColumn(5).data().toString());   //包装单位
        item_detail.insert("drug_type", index.siblingAtColumn(6).data().toString());   //药品类别，中药，西药
        item_detail.insert("drug_quality", index.siblingAtColumn(7).data().toString());   //药品类别，普药，特药
        item_detail.insert("retail_price", QString::number(index.siblingAtColumn(8).data().toDouble(),'f',2));   //零售价格
        item_detail.insert("purchase_price", QString::number(index.siblingAtColumn(9).data().toDouble(),'f',2));   //采购价格（药品基本信息表）
        item_detail.insert("item_code", index.siblingAtColumn(10).data().toString());   //药品编码
        item_detail.insert("fac_code", index.siblingAtColumn(11).data().toString());   //生产商
        item_detail.insert("min_unit", index.siblingAtColumn(12).data().toString());  //最小单位
        item_detail.insert("med_list_codg", index.siblingAtColumn(13).data().toString());  //医保编码
    }
    if(index.siblingAtColumn(14).isValid())
    {
        item_detail.insert("batch_no", index.siblingAtColumn(14).data().toString());  //批号
        item_detail.insert("manu_date", index.siblingAtColumn(15).data().toDate().toString("yyyy-MM-dd"));  //生产日期
        item_detail.insert("valid_date", index.siblingAtColumn(16).data().toDate().toString("yyyy-MM-dd"));  //效期
        item_detail.insert("purchase_price_sto", QString::number(index.siblingAtColumn(17).data().toDouble(),'f',2));  //采购价格（库存表）
        item_detail.insert("group_code", index.siblingAtColumn(18).data().toString());  //组（库存表）
        item_detail.insert("store_sum", index.siblingAtColumn(19).data().toString());  //库存数量（库存表）
    }
    if(index.siblingAtColumn(20).isValid())
    {
        item_detail.insert("out_bill_code", index.siblingAtColumn(20).data().toString());  //行唯一
        item_detail.insert("out_list_code", index.siblingAtColumn(21).data().toString());  //页唯一
        item_detail.insert("out_serial_code", index.siblingAtColumn(22).data().toString());
    }
    else
    {
        item_detail.insert("out_bill_code", "0");  //行唯一
        item_detail.insert("out_list_code", "");  //页唯一
        item_detail.insert("out_serial_code", "0");
    }


    if(ui->tabWidget->currentIndex() == 0)   //入库
    {
        ui->lePzwh->setText(item_detail["approve_info"]);
        ui->leScs->setText(item_detail["fac_name"]);
        ui->leLsjg->setText(item_detail["retail_price"]);
        ui->lePackQty->setText(item_detail["pack_qty"]);
        ui->lePackUnit->setText(item_detail["pack_unit"]);
        ui->lePh->setText("");
        ui->leScrq->setText("");
        ui->leXq->setText("");
        ui->leRksl->setText("");
        ui->leGrjg->setText(item_detail["purchase_price"]);
        ui->leGrje->setText("");
        ui->leFph->setText("");
        ui->leFprq->setText("");
        ui->leBz->setText("");
        int stsm = item_detail["store_sum"].toInt() / item_detail["pack_qty"].toInt();
        ui->leStoreSum->setText( QString::number(stsm) );

        if(ui->cbbMode_r->currentText() == "核准入库"
                || ui->cbbMode_r->currentText() == "入库退库"
                )
        {
            ui->lePh->setText(item_detail["batch_no"]);
            ui->leScrq->setText(item_detail["manu_date"]);
            ui->leXq->setText(item_detail["valid_date"]);
            ui->leRksl->setText( QString::number(stsm) );
            ui->leGrjg->setText(item_detail["purchase_price_sto"]);
        }
    }
    if(ui->tabWidget->currentIndex() == 1)   //出库
    {
        ui->lePzwh_2->setText(item_detail["approve_info"]);
        ui->leScs_2->setText(item_detail["fac_name"]);
        ui->leLsjg_2->setText(item_detail["retail_price"]);
        ui->lePackQty_2->setText(item_detail["pack_qty"]);
        ui->lePackUnit_2->setText(item_detail["pack_unit"]);
        ui->lePh_2->setText(item_detail["batch_no"]);
        ui->leScrq_2->setText(item_detail["manu_date"]);
        ui->leXq_2->setText(item_detail["valid_date"]);
        int stsm = item_detail["store_sum"].toInt() / item_detail["pack_qty"].toInt();
        ui->leStoreSum_2->setText( QString::number(stsm) );
        ui->leRksl_2->setText("");
        ui->leGrjg_2->setText(item_detail["purchase_price_sto"]);
        ui->leGrje_2->setText("");
        ui->leFph_2->setText("");
        ui->leFprq_2->setText("");
        ui->leBz_2->setText("");
    }
    if(ui->tabWidget->currentIndex() == 2)   //单据打印
    {

    }

}

void Form_yk_rk::on_tvSource_r_clicked(const QModelIndex &index)
{
    item_selected(index);
}

void Form_yk_rk::on_tvSource_r_doubleClicked(const QModelIndex &index)
{
    on_tvSource_r_clicked(index);
}

void Form_yk_rk::on_leRksl_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_rk::on_leGrjg_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_rk::calc_amount()
{
    if(!initialFinished)
    {
        return;
    }

    int in_num;
    double price;
    double tax;

    bool oki = false;   //入库转换
    bool okd = false;   //出库转换
    bool okt = false;   //税率转换

    if(ui->tabWidget->currentIndex() == 0)  //入库
    {
        in_num = ui->leRksl->text().toInt(&oki);
        price =  ui->leGrjg->text().toDouble(&okd);
        tax = ui->leTax->text().toDouble(&okt);

        if(oki && okd)
        {
            ui->leGrje->setText(QString::number(in_num * price, 'f', 2));
        }

        if(okt)
        {
            tax = tax / 100;    //
            ui->leTaxCost->setText(QString::number((in_num * price / (tax + 1 )) * tax , 'f', 2));  //税额
        }
    }

    if(ui->tabWidget->currentIndex() == 1)  //出库
    {
        in_num = ui->leRksl_2->text().toInt(&oki);
        price =  ui->leGrjg_2->text().toDouble(&okd);

        if(oki && okd)
        {
            ui->leGrje_2->setText(QString::number(in_num * price, 'f', 2));
        }
    }

}

void Form_yk_rk::on_pbAdd_clicked()
{
    if(!checkStatus("input_add_item"))
    {
        return;
    }

    QString input_check_no = get_input_check_no();

    if(input_check_no.isEmpty())
    {
        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意","找不到与录入项目相匹配的药品验收记录,\n是否强制入库？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
    }

    //入库数据插入临时表
    sq = "replace into tmp_pha_input ("
         "item_code, item_name, fac_code, fac_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
    sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
    sq += "drug_quality, retail_price, purchase_price,";   //药品普药特药类别，零售价格,采购价格
    sq += "med_list_codg,"; //医保码
    sq += "batch_no, manu_date, valid_date, num,";   //批号,生产日期,效期,数量
    sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
    sq += "out_bill_code, out_list_code, out_serial_code, input_check_no, group_code";//
    sq += ") values(";
    sq += "'" + item_detail["item_code"] + "',";//药品编码
    sq += "'" + item_detail["item_name"] + "',";//品名
    sq += "'" + item_detail["fac_code"] + "',";//生产商
    sq += "'" + item_detail["fac_name"] + "',";//生产商
    sq += "'" + item_detail["specs"] + "',";//规格
    sq += "'" + item_detail["approve_info"] + "',";//批准文号
    sq += "'" + item_detail["pack_qty"] + "',";//包装数量
    sq += "'" + item_detail["pack_unit"] + "',";//包装单位
    sq += "'" + item_detail["drug_type"] + "',";//药品类别，中药，西药
    sq += "'" + item_detail["drug_quality"] + "',";//药品类别，普药，特药
    sq += "'" + item_detail["retail_price"] + "',";//零售价格
    sq += "'" + ui->leGrjg->text().trimmed() + "',";//采购价格
    sq += "'" + item_detail["med_list_codg"] + "',";//医保码
    sq += "'" + ui->lePh->text().trimmed() + "',";//批号
    sq += "'" + ui->leScrq->text().trimmed() + "',";//生产日期
    sq += "'" + ui->leXq->text().trimmed() + "',";//效期
    sq += "'" + QString::number(ui->leRksl->text().toInt() * item_detail["pack_qty"].toInt()) + "',";//数量
    sq += "'" + ui->leFph->text().trimmed() + "',";//发票号
    sq += "'" + ui->leFprq->text().trimmed() + "',";//发票日期
    sq += "'" + ui->leBz->text().trimmed() + "',";//备注
    sq += "'" + item_detail["min_unit"] + "',";//备注
    sq += ui->leGrje->text()+ ",";//购入金额
    sq += item_detail["retail_price"] + " * (" + ui->leRksl->text().trimmed() +")," ;//零售金额
    sq += "'" + item_detail["out_bill_code"] + "',";//
    sq += "'" + item_detail["out_list_code"] + "',";//
    sq += "'" + item_detail["out_serial_code"] + "',";//
    sq += "'" + input_check_no + "',";//
    sq += "'" + item_detail["group_code"] + "'";//
    sq += ")";

    qDebug()<<"insert data to temporary table : "<< sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
        return ;
    }

    showList();

}

void Form_yk_rk::showList()
{
    //计算合计金额
    sq = "select sum(purchase_cost) from tmp_pha_input";
    qrm->exec(sq);
    qrm->next();
    double amount = qrm->value(0).toDouble();

    qDebug()<<"合计金额："<<ui->leAmount->text();
    sq = " select item_name 药品名称, SPECS 规格, fac_name 厂家, PACK_UNIT 包装单位, "
         " num / pack_qty 购入数量, purchase_cost 金额, item_code"
         " from tmp_pha_input order by atinc";

    qDebug()<<"待确认药品列表："<<sq;

    if(ui->tabWidget->currentIndex() == 0)
    {
        //入
        mdrd->setQuery(sq, pub::db_m);
        ui->tvDest_r->setModel(mdrd);
        int width = ui->tvDest_r->width();
        pub::setColumnWidth( ui->tvDest_r, "0.2^0.2^0.25^0.1^0.1^0.1^0^0^0^0^0^0^0", width, 20);
        ui->leAmount->setText(QString::number(amount, 'f', 2));
        ui->lePzwh->setText("");
        ui->leScs->setText("");
        ui->leLsjg->setText("");
        ui->lePh->setText("");
        ui->leScrq->setText("");
        ui->leXq->setText("");
        ui->leRksl->setText("");
        ui->leStoreSum->setText("");
        ui->leGrjg->setText("");
        ui->leGrje->setText("");
        ui->leFph->setText("");
        ui->leFprq->setText("");
        ui->leBz->setText("");
        ui->lePackQty->setText("");

    }
    if(ui->tabWidget->currentIndex() == 1)
    {
        //出
        mdcd->setQuery(sq, pub::db_m);
        ui->tvDest_c->setModel(mdcd);
        int width = ui->tvDest_c->width();
        pub::setColumnWidth( ui->tvDest_c, "0.2^0.2^0.25^0.1^0.1^0.1^0^0^0^0^0^0^0", width, 20);
        ui->leAmount_2->setText(QString::number(amount, 'f', 2));
        ui->lePzwh_2->setText("");
        ui->leScs_2->setText("");
        ui->leLsjg_2->setText("");
        ui->lePh_2->setText("");
        ui->leScrq_2->setText("");
        ui->leXq_2->setText("");
        ui->leRksl_2->setText("");
        ui->leGrjg_2->setText("");
        ui->leGrje_2->setText("");
        ui->leFph_2->setText("");
        ui->leFprq_2->setText("");
        ui->leBz_2->setText("");
        ui->lePackQty_2->setText("");
        ui->leStoreSum_2->setText("");
    }

    ui->leKey->clear();
    ui->leKey_2->clear();

}

bool Form_yk_rk::checkStatus(QString mod)
{
    QDate dt_m, dt_v, dt;
    int testInt;
    double testDouble;
    bool convertValue;
    QString tmpStr;

    if(item_detail["item_name_0"] != item_detail["item_name"] &&
            item_detail["specs_0"] != item_detail["specs"])
    {
        //检查录入状态是否有效
        QMessageBox::warning(this, "注意", "选定项目发生变更！");
        return false;
    }

    if(mod == "input_add_item")
    {
        //入库增加项目
        qDebug()<<"item_detail[drug_type] : "<<item_detail["drug_type"];

        if(item_detail["drug_type"] != "C")
        {
            //非草药，检查批准文号
            if(ui->lePzwh->text().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未选定项目！");
                return false;
            }
        }

        if(ui->lePh->text().trimmed().isEmpty()){
            QMessageBox::warning(this, "注意", "批号不可以空白！");
            return false;
        }

        dt_v = QDate::fromString(ui->leXq->text(), "yyyy-MM-dd");
        if(!dt_v.isValid()){
            QMessageBox::warning(this, "注意", "效期录入无效！");
            return false;
        }

        dt_m = QDate::fromString(ui->leScrq->text(), "yyyy-MM-dd");
        if(!dt_m.isValid()){
            QMessageBox::warning(this, "注意", "生产日期录入无效！");
            return false;
        }

        if(ui->leFprq->text().trimmed() != "--" )
        {
            dt = QDate::fromString(ui->leFprq->text(), "yyyy-MM-dd");
            if(!dt.isValid()){
                QMessageBox::warning(this, "注意", "发票日期录入无效！");
                return false;
            }
        }

        testInt = ui->leRksl->text().trimmed().toInt(&convertValue);
        if(testInt == 0)
        {
            QMessageBox::warning(this, "注意", "入库数量无效！");
            return false;
        }

        if(ui->cbbMode_r->currentText() == "入库退库")
        {
            if(testInt > ui->leStoreSum->text().toInt())
            {
                QMessageBox::warning(this, "注意", "退库数量不可以大于库存数量！");
                return false;
            }
        }

        if(ui->cbbMode_r->currentText() == "核准入库")
        {
            if(testInt != ui->leStoreSum->text().toInt())
            {
                QMessageBox::warning(this, "注意", "核准入库数量与出库数量不一致！");
                return false;
            }
        }

        testDouble = ui->leGrjg->text().trimmed().toDouble(&convertValue);
        if( qFuzzyCompare(testDouble, 0) || testDouble < 0)
        {
            QMessageBox::warning(this, "注意", "采购价格数值无效！");
            return false;
        }

        tmpStr = ui->leGrjg->text().trimmed();
        tmpStr = tmpStr.mid(tmpStr.indexOf("."));
        if( tmpStr.length() - 1 > 3 )
        {
            QMessageBox::warning(this, "注意", "采购价格数值小数位数超限！");
            return false;
        }
        testInt = dt_m.daysTo(QDate::currentDate());
        if(testInt < 0 )
        {
            QMessageBox::warning(this, "注意", "生产日期不应该小于当前日期！");
            return false;
        }

        testInt = QDate::currentDate().daysTo(dt_v);
        if(ui->cbbMode_r->currentText() != "入库退库" && testInt < 90 && ui->leRksl->text().toInt() > 0)
        {
            //非退库，效期过短，不可以正数入库
            QMessageBox::warning(this, "注意", "效期小于三个月，不可以入库！");
            return false;
        }
    }
    else if(mod == "input_save_invoice")
    {
        //入库单据保存
        if(ui->cbbStoreDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择库存单位！");
            return false;
        }

        if(ui->cbbMode_r->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择入库模式！");
            return false;
        }

        if(ui->cbbCompany->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择入库供货商！");
            return false;
        }

        if(mdrd->rowCount()<1)
        {
            QMessageBox::warning(this, "注意", "未录入项目数据！");
            return false;
        }

        if(ui->cbbMode_r->currentText() == "入库退库")
        {
            sq = "select group_code,item_name from tmp_pha_input";
            qrm->exec(sq);

            while(qrm->next())
            {
                sq = " select inp.company_code, comp.fac_name, inp.trade_name "
                     " from pha_com_input inp, pha_com_company comp"
                     " where comp.fac_code = inp.company_code and inp.group_code = '"
                        + qrm->value(0).toString() + "'";
                qro->exec(sq);
                qro->next();
                if(qro->value(1).toString() != ui->cbbCompany->currentText())
                {
                    QMessageBox::warning(this, "注意", "退库品种 "
                                         + qrm->value(1).toString() + " 采购来源与退库去向不一致！");
                    return false;
                }
            }
        }
    }
    else if(mod == "output_add_item")
    {
        //出库增加项目

        if(item_detail["drug_type"] != "C")
        {
            if(ui->lePzwh_2->text().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未选定项目！");
                return false;
            }
        }


        testInt = ui->leRksl_2->text().trimmed().toInt(&convertValue);
        if(testInt == 0)
        {
            QMessageBox::warning(this, "注意", "出库数量数值无效！");
            return false;
        }

        if(ui->leStoreSum_2->text().toInt()  < testInt)
        {
            QMessageBox::warning(this, "注意", "出库数量不可以大于库存数量！");
            return false;
        }
    }
    else if(mod == "output_save_invoice")
    {
        //出库单据保存
        if(ui->cbbStoreDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择库存单位！");
            return false;
        }

        if(ui->cbbMode_c->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择出库模式！");
            return false;
        }

        if(ui->cbbReceiveDept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择药品接收单位！");
            return false;
        }

        if(ui->cbbMode_c->currentText() != "报损" && ui->cbbMode_c->currentText() != "特殊出库" )
        {
            if( ui->cbbReceiveDept->currentText() == ui->cbbStoreDept->currentText() )
            {
                QMessageBox::warning(this, "注意", "药品接收单位与库存单位重复！");
                return false;
            }
        }
        else
        {
            if( ui->cbbReceiveDept->currentText() != ui->cbbStoreDept->currentText() )
            {
                QMessageBox::warning(this, "注意", "报损或特殊出库，药品接收单位必须与库存单位相同！");
                return false;
            }
        }

        if(mdcd->rowCount()<1)
        {
            QMessageBox::warning(this, "注意", "未录入项目数据！");
            return false;
        }
    }
    else
    {
        QMessageBox::warning(this, "注意", "校验模式选择无效！");
        return false;
    }
    return true;
}

void Form_yk_rk::on_pbSave_clicked()
{
    qDebug()<<"入库中间数据最终保存\n";
    if(!checkStatus("input_save_invoice"))
    {
        qDebug()<<"保存条件检查失败\n";
        return;
    }
    int pos;

    //入库类型, CLASS3_MEANING_CODE
    pos = pub::searchStr(mode_code_r, "^", ui->cbbMode_r->currentText());
    QString in_type = pub::getStr(mode_code_r, "^", pos + 1);
    QString class3_meaning_code = pub::getStr(mode_code_r, "^", pos + 2);

    //检索科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    //检索代货商代码
    pos = pub::searchStr(company_code, "^", ui->cbbCompany->currentText()) + 1;
    QString company = pub::getStr(company_code, "^", pos);

    //生成 in_list_code
    QString in_list_code ;
    sq = "select max(in_list_code) from pha_com_input where in_list_code like '" ;
    sq += dept_code + QDate::currentDate().toString("yyMMdd") + "%'";
    qDebug()<<"获取当前最大单据号:"<<sq;
    qro->exec(sq);
    qro->next();
    in_list_code = qro->value(0).toString();

    QString snStr;
    int snInt, serialInt = 0;
    if(in_list_code.isEmpty())
    {
        snStr = "001";
        snInt = 1;
    }
    else
    {
        QString sn = QString::number(in_list_code.right(3).toInt() + 1);
        snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
        snInt = snStr.toInt();
    }
    in_list_code = dept_code + QDate::currentDate().toString("yyMMdd") + snStr;

    //生成 group_code
    QString group_code;

    if(ui->cbbMode_r->currentText() == "一般入库"
            || ui->cbbMode_r->currentText() == "特殊入库"
            )
    {
        //一般入库，需要生成 group_code

        sq = "SELECT SEQ_PHA_COM_GROUP_CODE.NEXTVAL FROM DUAL";
        qDebug()<<"生成 group_code ："<<sq;
        if(qro->exec(sq))
        {
            qro->next();
            group_code = qro->value(0).toString();
        }
        else
        {
            QMessageBox::warning(this, "注意", "未能获取 group_code ！");
            qDebug()<<"group code 生成失败\n";
            return ;
        }
    }

    QSqlRecord rcd;
    QMap<QString, QString> para;
    para["dept_code"] = dept_code;  //库存单位
    para["group_code"] = group_code;   //批次号
    para["io_type"] = in_type;   //入库类型
    para["class3_meaning_code"] = class3_meaning_code;   //
    para["company"] = company; //供货公司
    para["state"] = "2"; //0 申请， 1审批， 2核准
    para["in_out"] = "in"; //入，出

    qDebug()<<" group_code is ："<<para["group_code"];

    if(ui->cbbMode_r->currentText() == "入库退库")
    {
        //退库进行负数计算
        para["mode"] = "-";
    }
    else
    {
        para["mode"] = "";
    }

    pub::db_o.transaction();
    QString tmpSql;
    QSqlQuery tmpQr;

    sq = "select * from tmp_pha_input ";
    qrm->exec(sq);
    while(qrm->next())
    {
        serialInt ++ ;//页面内部行号

        if(serialInt > MAX_LINES)
        {
            //每页限制行数
            serialInt = 1;
            snInt ++ ;  //单据号尾号
            QString sn = QString::number(snInt);
            snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
            in_list_code = dept_code + QDate::currentDate().toString("yyMMdd") + snStr;
        }

        para["list_code"] = in_list_code;   //入库单据号
        para["serial_code"] = QString::number(serialInt);   //

        //临时表当前行数据
        rcd = qrm->record();
        if(ui->cbbMode_r->currentText() == "入库退库" || ui->cbbMode_r->currentText() == "核准入库")
        {
            //退库，核准入库，使用旧 group_code
            para["group_code"] = rcd.value("group_code").toString();
        }

        //生成 in_bill_code
        tmpSql = "SELECT SEQ_PHA_INBILL_ID.NEXTVAL FROM DUAL";
        tmpQr = pub::db_o.exec(tmpSql);
        tmpQr.next();
        para["bill_code"] = tmpQr.value(0).toString();

        //保存 pha_com_input
        if(!ins_input(rcd, para))
        {
            pub::db_o.rollback();
            qDebug()<<"pha_com_input 保存失败，数据回滚\n";
            return;
        }

        //保存 pha_com_storage
        if(!ins_storage(rcd, para))
        {
            qDebug()<<"pha_com_storage 保存失败，数据回滚\n";
            pub::db_o.rollback();
            return;
        }

        if(ui->cbbMode_r->currentText() == "核准入库")
        {
            //检索供货库房代码
            pos = pub::searchStr(store_depts, "^", ui->cbbCompany->currentText()) + 1;

            sq = "update pha_com_output set out_state = '2' ";
            sq += " WHERE DRUG_DEPT_CODE = '" + pub::getStr(store_depts, "^", pos) + "'  ";
            sq += " AND  OUT_BILL_CODE = " + rcd.value("out_bill_code").toString();
            sq += " AND  SERIAL_CODE = " + rcd.value("out_serial_code").toString();
            qDebug()<<"change pha_com_output : " << sq;
            pub::db_o.exec(sq);
        }
    }
    pub::db_o.commit();

    qrm->exec("delete from tmp_pha_input");
    showList();
    change_lock_status("in", true);
    qDebug()<<"入库中间数据转储成功\n";
}

bool Form_yk_rk::ins_storage(QSqlRecord rcd, QMap<QString,QString> para)
{
    if(para["in_out"] == "out")
    {
        //出库, 修改已经存在的记录
        sq = "UPDATE PHA_COM_STORAGE SET ";
        sq += " STORE_SUM = STORE_SUM - (" + para["mode"] + rcd.value("num").toString() + "),"; //库存数量
        sq += " STORE_COST  = STORE_COST - (" + para["mode"] + rcd.value("purchase_cost").toString() + "),"; // 库存金额
        sq += " BILL_CODE   = " + para["bill_code"] + ",";// 入库单流水号
        sq += " SERIAL_CODE = " + para["serial_code"] +","; // 序号
        sq += " TARGET_DEPT = '" + para["receive_dept_code"]  + "',";  //最后变更源
        sq += " CLASS2_CODE = '" + para["io_type"] + "',";// 操作代码
        sq += " OPER_CODE   = '" + pub::usr_code + "', ";//操作员
        sq += " OPER_DATE   = SYSDATE ";//日期
        sq += " WHERE  DRUG_DEPT_CODE = '" + para["dept_code"] + "'"  ;//库存单位
        sq += " AND DRUG_CODE  = '" + rcd.value("item_code").toString() + "'" ;  //药品编码
        sq += " AND BATCH_NO = '" + rcd.value("batch_no").toString() + "'";  //批号"
        sq += " AND GROUP_CODE = '" + rcd.value("group_code").toString() + "'" ; //批次号

        qDebug()<<" UPDATE PHA_COM_STORAGE : "<<sq;
        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 pha_com_storage 错误！\n" + pub::db_o.lastError().text() );
            return false;
        }
        return true;
    }

    //检索pha_com_storage 中是否存在记录，确定进行变更或者插入。对于入库有用，出库无意义
    sq = " select drug_code from pha_com_storage where ";
    sq += " DRUG_DEPT_CODE = '" + para["dept_code"] + "'";  //库存单位
    sq += " AND DRUG_CODE  = '" + rcd.value("item_code").toString() + "'";   //药品编码
    sq += " AND BATCH_NO = '" + rcd.value("batch_no").toString() + "'";  //批号"
    sq += " AND GROUP_CODE = '" + para["group_code"] + "'" ; //批次号

    qDebug()<<"检索 pha_com_storage : "<<sq;

    QSqlQuery tmpQr = pub::db_o.exec(sq);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "检索 pha_com_storage 发生错误！\n" + pub::db_o.lastError().text() );
        qDebug()<<"检索 pha_com_storage 发生错误 : " << pub::db_o.lastError().text();
        return false;
    }

    tmpQr.next();

    if(tmpQr.isNull(0))
    {
        //未找到旧数据，插入新记录
        sq = "INSERT INTO PHA_COM_STORAGE (";
        sq += " DRUG_DEPT_CODE, DRUG_CODE, GROUP_CODE, BATCH_NO, ";// --库存科室 -药品编码 -批次号 -批号
        sq += " TRADE_NAME, SPECS, DRUG_TYPE, DRUG_QUALITY,";// --药品商品名 -规格 -药品类别 -药品性质
        sq += " RETAIL_PRICE, WHOLESALE_PRICE, PURCHASE_PRICE, PACK_UNIT, "; //--零售价 -批发价 -实进价 -包装单位
        sq += " PACK_QTY, MIN_UNIT, SHOW_FLAG, SHOW_UNIT, ";//-包装数 -最小单位 -显示的单位标记 -显示的单位
        sq += " VALID_DATE,STORE_SUM, STORE_COST, PRODUCER_CODE, ";//-有效期 -库存数量 -库存金额 -生产厂家
        sq += " PLACE_CODE, TARGET_DEPT, BILL_CODE, SERIAL_CODE, ";//--货位号 -目标科室 -单据号 -单据序号
        sq += " CLASS2_CODE, MARK,"; // --库存操作类型0310入,0320出 -备注
        sq += " OPER_CODE, OPER_DATE, STATE, INVOICE_NO,";// --操作员 -操作日期 -状态 -发票号
        sq += " MANU_DATE, MED_LIST_CODG ";     //生产日期， 医保药品编码
        sq += " )  VALUES( ";
        sq += "'" + para["dept_code"] + "',"  ;//库存科室
        sq += "'" + rcd.value("item_code").toString() + "'," ;//--药品编码
        sq += "'" + para["group_code"] + "',"  ;// --批次号
        sq += "'" + rcd.value("batch_no").toString()  + "',"  ; //--批号
        sq += "'" + rcd.value("item_name").toString()  + "',"  ;  //--药品商品名
        sq += "'" + rcd.value("specs").toString()  + "',"  ; //--规格
        sq += "'" + rcd.value("drug_type").toString() + "',"  ;   //--药品类别
        sq += "'" + rcd.value("drug_quality").toString()   + "',"  ;  //--药品性质
        sq += rcd.value("retail_price").toString()  + ","  ;   //--零售价
        sq += " 0 ,";  //--批发价
        sq += rcd.value("purchase_price").toString()   + ","  ;   //--实进价
        sq += "'" + rcd.value("pack_unit").toString()  + "',"  ;  //  --包装单位
        sq += rcd.value("pack_qty").toString()   + ","  ;  // --包装数
        sq += "'" + rcd.value("min_unit").toString()  + "',"  ;    //--最小单位
        sq += "'0',";//--显示的单位标记
        sq += "'',"; //--显示的单位
        sq += " to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd') ,";//-有效期
        sq += rcd.value("num").toString() + ","  ;   //--库存数量
        sq += rcd.value("purchase_cost").toString() + ","  ;  // --库存金额
        sq += "'" + rcd.value("fac_code").toString()  + "',"  ;  // --生产厂家
        sq += "'' ,";//       --货位号
        sq += "'" + para["dept_code"] + "',"  ;  // --目标科室
        sq += para["bill_code"] + ","  ;  // --单据号
        sq += para["serial_code"] + ", "; //  --单内序号
        sq += "'" + para["io_type"] + "',"  ;  //  --库存操作类型M1门诊发药,M2门诊退药,Z1住院发药,Z2住院退药……
        sq += "'" + rcd.value("memo").toString() + "',"  ;  //  --备注
        sq += "'" + pub::usr_code + "' , "; //      --操作员
        sq += " SYSDATE, ";    //-操作日期
        sq += " '1', '',";//
        sq += " to_date('" + rcd.value("manu_date").toString() + "','yyyy-mm-dd') ,";//生产日期
        sq += "'" + rcd.value("med_list_codg").toString() + "'"  ;  //医保编码
        sq += ")";

        qDebug()<<"pha_com_storage 插入新记录 : "<<sq;

        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", " pha_com_storage 插入新记录错误！\n" + pub::db_o.lastError().text() );
            qDebug()<<"pha_com_storage 错误 : "<<pub::db_o.lastError().text();
            return false;
        }
    }
    else
    {
        //修改已经存在的记录
        sq = "UPDATE PHA_COM_STORAGE SET ";
        sq += " STORE_SUM = STORE_SUM + (" + para["mode"] + rcd.value("num").toString() + "),"; //库存数量
        sq += " STORE_COST  = STORE_COST + (" + para["mode"] + rcd.value("purchase_cost").toString() + "),"; // 库存金额
        sq += " BILL_CODE   = " + para["bill_code"] + ",";// 入库单流水号
        sq += " SERIAL_CODE = " + para["serial_code"] + ","; // 序号
        sq += " TARGET_DEPT = '" + para["company"]  + "',";  //最后变更源
        sq += " CLASS2_CODE = '" + para["io_type"] + "',";// 操作代码
        sq += " OPER_CODE   = '" + pub::usr_code + "', ";//操作员
        sq += " OPER_DATE   = SYSDATE ";//日期
        sq += " WHERE  DRUG_DEPT_CODE = '" + para["dept_code"] + "'"  ;//库存单位
        sq += " AND DRUG_CODE  = '" + rcd.value("item_code").toString() + "'" ;  //药品编码
        sq += " AND BATCH_NO = '" + rcd.value("batch_no").toString() + "'";  //批号"
        sq += " AND GROUP_CODE = '" + para["group_code"] + "'" ; //批次号

        qDebug()<<" UPDATE PHA_COM_STORAGE : "<<sq;
        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 pha_com_storage 错误！\n" + pub::db_o.lastError().text() );
            return false;
        }
    }

    return true;

}

bool Form_yk_rk::ins_input(QSqlRecord rcd, QMap<QString, QString> para)
{
    sq = " INSERT INTO PHA_COM_INPUT ( ";
    sq += "DRUG_DEPT_CODE, IN_BILL_CODE, GROUP_CODE, IN_LIST_CODE, "; //库存科室 ,入库单流水号,批次号,入库单据号
    sq += "IN_TYPE, CLASS3_MEANING_CODE, SERIAL_CODE,";//入库类型, 入库分类, 序号
    sq += "OUT_BILL_CODE, OUT_SERIAL_CODE, OUT_LIST_CODE, "; //出库单号 - 出库单序号 - 出库单据号
    sq += "DRUG_CODE, TRADE_NAME, DRUG_TYPE, DRUG_QUALITY, SPECS,";//-药品编码 -药品商品名 -药品类别 -药品性质 -规格
    sq += "PACK_UNIT, PACK_QTY, MIN_UNIT, SHOW_FLAG, SHOW_UNIT, "; //-包装单位 -包装数 -最小单位 -显示的单位标记 -显示的单位
    sq += "BATCH_NO,MANU_DATE, VALID_DATE, PRODUCER_CODE, COMPANY_CODE, "; //-批号 -生产日期 -有效期 -生产厂家 -供货单位代码
    sq += "RETAIL_PRICE, WHOLESALE_PRICE, PURCHASE_PRICE, ";//-零售价 -批发价 -购入价
    sq += "IN_NUM, RETAIL_COST, WHOLESALE_COST, PURCHASE_COST ,"; // -购入数量 -零售金额 -批发金额 -购入金额
    sq += "STORE_NUM, STORE_COST, SPECIAL_FLAG, IN_STATE,";//--入库后库存 -入库后金额 -特殊标记，1是，0否 -入库状态，0-申请，1-审批（发票入库），2-核准
    sq += "APPLY_NUM, APPLY_OPERCODE, APPLY_DATE, "; //-申请入库量 -申请入库操作员 -申请入库日期
    sq += "EXAM_NUM, EXAM_OPERCODE, EXAM_DATE,";//-审批数量 -审批人（药库发票入库人） -审批日期（药库发票入库日期）
    sq += "APPROVE_OPERCODE , APPROVE_DATE ,";//-核准人 -核准日期
    sq += "PLACE_CODE , RETURN_NUM,";//-货位码 -退库数量
    sq += "APPLY_NUMBER, MED_ID, INVOICE_NO, ";//-申请序号 -制剂序号－生产序号或检验序号 -发票号
    sq += "DELIVERY_NO, TENDER_NO, ACTUAL_RATE, ";//--送药单流水号 -招标序号 -实际扣率 "
    sq += "CASH_FLAG, PAY_STATE, ";//    -现金标志 结款状态 0 未 1 未全 2 付清
    sq += "OPER_CODE , OPER_DATE ," ;//-操作员 -操作日期
    sq += "MARK, EXT_CODE, EXT_CODE1, EXT_CODE2 ,"; //-备注 -扩展字段 -扩展字段1 -扩展字段1
    sq += "IS_TENDER_OFFER, PURCHARSE_PRICE_FIRSTTIME, INVOICE_DATE,";//-招标标记  -一般入库时的购入价 -发票上的发票时间
    sq += "IN_DATE, SOURCE_COMPANY_TYPE, med_list_codg";//

    sq += " ) values (";

    sq += "'" + para["dept_code"] + "' ,";   //库存科室代码
    sq += para["bill_code"] + " ,";   //入库单流水号

    sq += "'" + para["group_code"] + "' ,";   //批次号
    sq += "'" + para["list_code"] + "' ,";   //入库单据号
    sq += "'" + para["io_type"] + "' ,";   //入库类型
    sq += "'" + para["class3_meaning_code"] + "' ,";
    sq += para["serial_code"] + ",";   //
    sq += rcd.value("out_bill_code").toString() + ",0," ;//出库单号 - 出库单序号
    sq += "'" + rcd.value("out_list_code").toString() + "',";   // 出库单据号
    sq += "'" + rcd.value("item_code").toString() + "'," ; //-药品编码
    sq += "'" + rcd.value("item_name").toString() + "'," ; //-药品商品名
    sq += "'" + rcd.value("drug_type").toString() + "'," ; //-药品类别
    sq += "'" + rcd.value("drug_quality").toString() + "'," ; //-药品性质
    sq += "'" + rcd.value("specs").toString() + "'," ; //-规格
    sq += "'" + rcd.value("pack_unit").toString() + "'," ; //包装单位
    sq += "'" + rcd.value("pack_qty").toString() + "'," ; //包装数
    sq += "'" + rcd.value("min_unit").toString() + "'," ; //最小单位
    sq += "'0','',";    // -显示的单位标记 -显示的单位
    sq += "'" + rcd.value("batch_no").toString() + "'," ; //批号
    sq += "to_date('" + rcd.value("manu_date").toString() + "','yyyy-mm-dd')," ; //生产日期
    sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd')," ; //有效期
    sq += "'" + rcd.value("fac_code").toString() + "'," ; //生产厂家
    sq += "'" + para["company"] + "'," ; //供货单位代码
    sq += rcd.value("retail_price").toString() + ",0 ," ; //-零售价 -批发价
    sq += rcd.value("purchase_price").toString() + ", " ; //-购入价
    sq += para["mode"] + rcd.value("num").toString() + ", " ; //-购入数量
    sq += para["mode"] + rcd.value("retail_cost").toString() + ",0 ," ; //-零售金额 -批发金额
    sq += para["mode"] + rcd.value("purchase_cost").toString() + "," ; //-购入金额

    QString tmpSql = "select STORE_SUM,STORE_COST from PHA_COM_STOCKINFO where DRUG_CODE = '"
            + rcd.value("item_code").toString() + "' and DRUG_DEPT_CODE = '" + para["dept_code"] + "' ";
    QString  store_sum, store_cost;
    qDebug()<<"检索品种当前库存数量 ："<<tmpSql;

    QSqlQuery tmpQr = pub::db_o.exec(tmpSql);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "读取 pha_com_stockinfo 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    if(tmpQr.next())
    {
        store_sum = tmpQr.value(0).toString();
        store_cost = tmpQr.value(1).toString();
    }else{
        store_sum = "0";
        store_cost = "0";
    }

    sq += "(" + store_sum + ") + (" + para["mode"] + rcd.value("num").toString() + ")," ; //入库后库存
    sq += "(" + store_cost + ") + (" + para["mode"] + rcd.value("purchase_cost").toString() + ")," ; //-入库后金额
    sq += "'0','" + para["state"] + "',"; //-特殊标记，1是，0否 -入库状态，0-申请，1-审批（发票入库），2-核准
    sq += para["mode"] + rcd.value("num").toString() + "," ;//-申请入库量
    sq += "'" + pub::usr_code + "', SYSDATE, "; // -申请入库操作员 -申请入库日期
    sq += para["mode"] + rcd.value("num").toString() + "," ;//--审批数量
    sq += "'" + pub::usr_code + "', SYSDATE, "; // -申请入库操作员 -申请入库日期
    sq += "'" + pub::usr_code + "', SYSDATE, "; // -核准人 -核准日期
    sq += "'' , 0,";//-货位码 -退库数量
    sq += "'" + para["in_bill_code"] + "' ,'', ";  //申请序号 -制剂序号－生产序号或检验序号
    sq += "'" + rcd.value("invo_no").toString() + "'," ;//-发票号
    sq += "'','',0,'','',"; //--送药单流水号 -招标序号 -实际扣率 -现金标志 结款状态 0 未 1 未全 2 付清
    sq += "'" + pub::usr_code + "', SYSDATE, "; // -操作员 -操作日期
    sq += "'" + rcd.value("memo").toString() + "','','',''," ;//-备注 -扩展字段 -扩展字段1 -扩展字段1
    sq += "'0', '0', "  ;//-招标标记  -一般入库时的购入价
    if(rcd.value("invo_date").toString() == "--")//-发票上的发票时间
    {
        sq += "to_date('0001-01-01','yyyy-mm-dd')," ;
    }else{
        sq += "to_date('" + rcd.value("invo_date").toString() + "','yyyy-mm-dd')," ;
    }

    tmpSql = "select fac_name from pha_com_company where fac_code = '" + para["company"] + "' ";
    tmpQr = pub::db_o.exec(sq);

    QString company_type;
    if(tmpQr.next())
    {
        company_type = "2";
    }else{
        company_type = "1";
    }

    sq += "SYSDATE, '" + company_type + "',";//入库日期，来源类别 1院内， 2外购
    sq += "'" + rcd.value("med_list_codg").toString() + "'";
    sq += ")";

    qDebug()<<"插入入库记录 pha_com_input : "<<sq<<"\n";

    pub::db_o.exec(sq);

    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "插入 pha_com_input 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    if(!rcd.value("input_check_no").toString().isEmpty())
    {
        sq = " update pha_com_input_check"
             " set in_state = '1',"
             " exam_num = apply_num,"
             " exam_date = sysdate,"
             " exam_opercode = '%1',"
             " in_bill_code = '%2',"
             " serial_code = '%3',"
             " in_list_code = '%4'"
             " where input_check_no = %5";
        sq = sq.arg(pub::usr_code)
                .arg(para["bill_code"])
                .arg(para["serial_code"])
                .arg(para["list_code"])
                .arg(rcd.value("input_check_no").toString());
        qDebug()<<"变更 pha_com_input_check : "<<sq<<"\n";
        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::warning(this, "注意", "变更 pha_com_input_check 失败！\n" + pub::db_o.lastError().text() );
            return false;
        }
    }

    return true;
}

void Form_yk_rk::on_pbRemove_clicked()
{
    if(ui->tvDest_r->currentIndex().isValid())
    {
        QString item_code = ui->tvDest_r->currentIndex().siblingAtColumn(6).data(0).toString();
        qrm->exec("delete from tmp_pha_input where item_code = '" + item_code + "'");
        showList();
    }
    else
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
}

void Form_yk_rk::on_pbSearch_3_clicked()
{


}

void Form_yk_rk::on_leKey_3_returnPressed()
{

}

void Form_yk_rk::search_item(QString key, QSqlQueryModel *md, QTableView *tv, QString mode)
{
    int pos;
    QString target_dept_code, dept_code;

    //非项目维护模式，检查当前工作库房
    if(mode != "item_config" && ui->cbbStoreDept->currentText().isEmpty())
    {
        QMessageBox::warning(this, "注意", "未指定当前工作库房！" );
        return;
    }
    else
    {
        pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
        dept_code = pub::getStr(store_depts, "^", pos);
    }

    //出入库目标单位
    if(ui->tabWidget->currentIndex() == 0)
    {
        //入
        if(ui->cbbCompany->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定目标单位！" );
            return;
        }
        pos = pub::searchStr(company_code, "^", ui->cbbCompany->currentText()) + 1;
        target_dept_code = pub::getStr(company_code, "^", pos);

        if(ui->ckb_checked_only->isChecked() &&
                    (mode == "一般入库" || mode == "核准入库"))
        {
            //只提取已经验收过的入库记录
            search_checked(target_dept_code, dept_code);
            return;
        }

    }
    else if(ui->tabWidget->currentIndex() == 1)
    {
        //出
        if(mode == "报损" || mode == "特殊出库" )
        {
            target_dept_code = dept_code;
        }
        else
        {
            if(ui->cbbReceiveDept->currentText().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未指定目标单位！" );
                return;
            }
            pos = pub::searchStr(store_depts, "^", ui->cbbReceiveDept->currentText()) + 1;
            target_dept_code = pub::getStr(store_depts, "^", pos);
        }
    }
    else if(ui->tabWidget->currentIndex() == 3)
    {
        //item configuration

    }
    else
    {
        QMessageBox::warning(this, "注意", "工作模式无效！" );
        return;
    }

    if(mode == "一般入库" || mode == "特殊入库")
    {
        sq = " select pha.TRADE_NAME 药品名称, pha.SPECS 规格, "
             " f_c.fac_name 厂家, pha.APPROVE_INFO, "//0 - 3
             " pha.PACK_QTY, pha.PACK_UNIT, pha.DRUG_TYPE, "
             " pha.DRUG_QUALITY, pha.RETAIL_PRICE, pha.PURCHASE_PRICE,"//4 - 9
             " pha.DRUG_CODE , pha.PRODUCER_CODE fac_code, "
             " pha.min_unit, comp.med_list_codg";//10 - 13
        sq += " from pha_com_baseinfo pha "
              " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = pha.PRODUCER_CODE "
              " LEFT JOIN fin_com_compare comp ON comp.FIXMEDINS_HILIST_ID = DRUG_CODE ";
        sq += " where pha.VALID_STATE = '1' ";
        sq += " and (pha.SPELL_CODE like '%" + key.toUpper() + "%' or pha.TRADE_NAME like '%" + key + "%' )";
        sq += " order by pha.TRADE_NAME";

    }
    else if(mode == "一般出库" || mode == "报损" || mode == "特殊出库")
    {
        sq = " select pha.TRADE_NAME 药品名称, pha.SPECS 规格, f_c.fac_name 厂家, pha.APPROVE_INFO, "//0 - 3
             " pha.PACK_QTY, pha.PACK_UNIT, pha.DRUG_TYPE, pha.DRUG_QUALITY, pha.RETAIL_PRICE, pha.PURCHASE_PRICE,"//4 - 9
             " pha.DRUG_CODE , pha.PRODUCER_CODE fac_code, pha.min_unit, comp.med_list_codg, ";//10 - 13
        sq += " sto.batch_no 批号, sto.manu_date, sto.valid_date, sto.PURCHASE_PRICE, sto.group_code, sto.store_sum "; //14 - 19
        sq += " from pha_com_baseinfo pha "
              " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = pha.PRODUCER_CODE "
              " LEFT JOIN fin_com_compare comp ON comp.FIXMEDINS_HILIST_ID = DRUG_CODE ";
        sq += " join pha_com_storage sto on PHA.drug_code = sto.drug_code "
              " and drug_dept_code = '" + dept_code + "' and sto.store_sum > 0 ";
        sq += " where pha.VALID_STATE = '1' ";
        sq += " and (pha.SPELL_CODE like '%" + key.toUpper() + "%' or pha.TRADE_NAME like '%" + key + "%' )";
        sq += " order by pha.TRADE_NAME";

    }
    else if(mode == "核准入库")
    {
        sq = " select T.TRADE_NAME 药品名称, T.SPECS 规格, F.fac_name 厂家, S.APPROVE_INFO, " //0 - 3
             " T.PACK_QTY, T.PACK_UNIT, T.DRUG_TYPE, T.DRUG_QUALITY, T.RETAIL_PRICE, T.PURCHASE_PRICE," //4 - 9
             " T.DRUG_CODE , T.PRODUCER_CODE , T.min_unit, c.med_list_codg, ";//10 - 13
        sq += " T.batch_no 批号, T.manu_date, T.valid_date, T.PURCHASE_PRICE, T.group_code, T.OUT_NUM - T.RETURN_NUM ,"; //14 - 19
        sq += " T.OUT_BILL_CODE, T.OUT_LIST_CODE, T.SERIAL_CODE";//20 - 22
        sq += " FROM PHA_COM_OUTPUT T ";
        sq += " left join PHA_COM_BASEINFO S on S.DRUG_CODE = T.DRUG_CODE ";
        sq += " left join PHA_COM_COMPANY F on F.FAC_CODE = T.PRODUCER_CODE ";
        sq += " left join fin_com_compare c on c.FIXMEDINS_HILIST_ID = t.DRUG_CODE ";
        sq += " where T.OUT_STATE = '1'";
        sq += " AND T.DRUG_STORAGE_CODE = '" + dept_code + "'";
        sq += " AND T.DRUG_DEPT_CODE = '" + target_dept_code + "' ";
        sq += " AND T.OUT_NUM - T.RETURN_NUM > 0";
        sq += " and (S.SPELL_CODE like '%" + key.toUpper() + "%' or S.TRADE_NAME like '%" + key + "%' )";
        sq += " order by S.TRADE_NAME";
    }
    else if(mode.indexOf("退库") > 0)
    {
        QString dptcd;
        if(mode == "出库退库")
        {
            dptcd = target_dept_code;
        }
        else if(mode == "入库退库")
        {
            dptcd = dept_code;
        }
        else
        {
            QMessageBox::warning(this, "注意", "退库方式无效！" );
            return;
        }
        sq = " select pha.TRADE_NAME 药品名称, pha.SPECS 规格, f_c.fac_name 厂家, pha.APPROVE_INFO, "//0 - 3
             " pha.PACK_QTY, pha.PACK_UNIT, pha.DRUG_TYPE, pha.DRUG_QUALITY, pha.RETAIL_PRICE, pha.PURCHASE_PRICE," //4 - 9
             " pha.DRUG_CODE , pha.PRODUCER_CODE fac_code, pha.min_unit, sto.med_list_codg, ";//10 - 13
        sq += " sto.batch_no 批号, sto.manu_date, sto.valid_date, sto.PURCHASE_PRICE, sto.group_code, sto.store_sum "; //14 - 19
        sq += " from pha_com_storage sto ";
        sq += " left join pha_com_baseinfo pha on sto.drug_code = pha.drug_code ";
        sq += " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = sto.PRODUCER_CODE ";
        sq += " where sto.store_sum > 0 ";
        sq += " and sto.drug_dept_code = '" + dptcd + "' ";
        sq += " and (pha.SPELL_CODE like '%" + key.toUpper() + "%' or pha.TRADE_NAME like '%" + key + "%' )";
        sq += " order by pha.TRADE_NAME";

    }
    else
    {
        QMessageBox::warning(this, "注意", "出入库方式无效！" );
        return;

    }

    qDebug()<<"药品目录检索："<<sq;
    md->setQuery(sq, pub::db_o);

    tv->setModel(md);
    int width = tv->width();
    if(mode == "一般出库"
            || mode == "报损"
            || mode == "特殊出库"
            || mode.indexOf("退库") > 0
            )
    {
        pub::setColumnWidth(tv, "0.27^0.2^0.27^0^0^0^0^0^0^0^0^0^0^0^0.2^0^0^0^0", width, 20);
    }
    else
    {
        pub::setColumnWidth(tv, "0.3^0.2^0.4^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0", width, 25);
    }

    //检索成功之后，禁止修改库存单位
    if(ui->tabWidget->currentIndex() == 0)
    {
        change_lock_status("in", false);
    }
    else if(ui->tabWidget->currentIndex() == 1)
    {
        change_lock_status("out", false);
    }

}

void Form_yk_rk::on_lePh_returnPressed()
{
    if(ui->lePh->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leScrq->setFocus();
        ui->leScrq->selectAll();
    }
}

void Form_yk_rk::on_leScrq_returnPressed()
{
    ui->leXq->setFocus();
    ui->leXq->selectAll();
}

void Form_yk_rk::on_leXq_returnPressed()
{
    ui->leRksl->setFocus();
}

void Form_yk_rk::on_pbSearch_2_clicked()
{
    search_item(ui->leKey_2->text().trimmed(),
                mdcs,
                ui->tvSource_c,
                ui->cbbMode_c->currentText());
}

void Form_yk_rk::on_leKey_2_returnPressed()
{
    if(ui->leKey_2->text().trimmed().isEmpty())
    {
        return;
    }
    on_pbSearch_2_clicked();
}


void Form_yk_rk::on_pbAdd_2_clicked()
{
    if(!checkStatus("output_add_item"))
    {
        return;
    }

    //出库数据插入临时表
    sq = "replace into tmp_pha_input ("
         "item_code, item_name, fac_code, fac_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
    sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
    sq += "drug_quality, retail_price, purchase_price,";   //药品普药特药类别，零售价格,采购价格
    sq += "med_list_codg, group_code,"; //医保码, 组
    sq += "batch_no, manu_date, valid_date, num,";   //批号,生产日期,效期,数量
    sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost, ";   //发票号, 发票日期, 备注， 购入金额，零售金额
    sq += "out_bill_code, out_list_code, out_serial_code ";   //
    sq += ") values(";
    sq += "'" + item_detail["item_code"] + "',";//药品编码
    sq += "'" + item_detail["item_name"] + "',";//品名
    sq += "'" + item_detail["fac_code"] + "',";//生产商
    sq += "'" + item_detail["fac_name"] + "',";//生产商
    sq += "'" + item_detail["specs"] + "',";//规格
    sq += "'" + item_detail["approve_info"] + "',";//批准文号
    sq += "'" + item_detail["pack_qty"] + "',";//包装数量
    sq += "'" + item_detail["pack_unit"] + "',";//包装单位
    sq += "'" + item_detail["drug_type"] + "',";//药品类别，中药，西药
    sq += "'" + item_detail["drug_quality"] + "',";//药品类别，普药，特药
    sq += "'" + item_detail["retail_price"] + "',";//零售价格
    sq += "'" + item_detail["purchase_price_sto"] + "',";//采购价格
    sq += "'" + item_detail["med_list_codg"] + "',";//医保码
    sq += "'" + item_detail["group_code"] + "',";//组
    sq += "'" + ui->lePh_2->text().trimmed() + "',";//批号
    sq += "'" + ui->leScrq_2->text().trimmed() + "',";//生产日期
    sq += "'" + ui->leXq_2->text().trimmed() + "',";//效期
    sq += "'" + QString::number(ui->leRksl_2->text().toInt() * item_detail["pack_qty"].toInt()) + "',";//数量
    sq += "'" + ui->leFph_2->text().trimmed() + "',";//发票号
    sq += "'" + ui->leFprq_2->text().trimmed() + "',";//发票日期
    sq += "'" + ui->leBz_2->text().trimmed() + "',";//备注
    sq += "'" + item_detail["min_unit"] + "',";//备注
    sq += ui->leGrje_2->text()+ ",";//购入金额
    sq += item_detail["retail_price"] + " * (" + ui->leRksl_2->text().trimmed() +")," ;//零售金额
    sq += "'" + item_detail["out_bill_code"] + "',";//
    sq += "'" + item_detail["out_list_code"] + "',";//
    sq += "'" + item_detail["out_serial_code"] + "'";//
    sq += ")";

    qDebug()<<"insert data to temporary table : "<< sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
        return ;
    }

    showList();
}

void Form_yk_rk::on_tvSource_c_clicked(const QModelIndex &index)
{
    item_selected(index);
}

void Form_yk_rk::on_tvSource_c_doubleClicked(const QModelIndex &index)
{
    on_tvSource_c_clicked(index);
}

//void Form_yk_rk::on_tvSource_r_3_clicked(const QModelIndex &index)
//{
//    item_selected(index);
//}

//void Form_yk_rk::on_tvSource_r_3_doubleClicked(const QModelIndex &index)
//{
//    on_tvSource_r_3_clicked(index);
//}

void Form_yk_rk::on_leRksl_2_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_rk::on_pbRemove_2_clicked()
{
    if(ui->tvDest_c->currentIndex().isValid())
    {
        QString item_code = ui->tvDest_c->currentIndex().siblingAtColumn(6).data(0).toString();
        qrm->exec("delete from tmp_pha_input where item_code = '" + item_code + "'");
        showList();
    }
    else
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
}

void Form_yk_rk::on_pbSave_2_clicked()
{
    qDebug()<<"出库中间数据最终保存\n";
    if(!checkStatus("output_save_invoice"))
    {
        qDebug()<<"保存条件检查未通过\n";
        return;
    }
    int pos;

    //出库类型
    pos = pub::searchStr(mode_code_c, "^", ui->cbbMode_c->currentText());
    QString out_type = pub::getStr(mode_code_c, "^", pos + 1);

    //CLASS3_MEANING_CODE
    QString class3_meaning_code = pub::getStr(mode_code_c, "^", pos + 2);

    //检索目标科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    //检索输入科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbbReceiveDept->currentText()) + 1;
    QString receive_dept_code = pub::getStr(store_depts, "^", pos);

    //生成 out_list_code
    QString out_list_code ;
    sq = "select max(out_list_code) from pha_com_output where out_list_code like '" ;
    sq += dept_code + QDate::currentDate().toString("yyMMdd") + "%'";
    qDebug()<<"获取当前最大单据号:"<<sq;
    qro->exec(sq);
    qro->next();
    out_list_code = qro->value(0).toString();

    QString snStr;
    int snInt, serialInt = 0;
    if(out_list_code.isEmpty())
    {
        snStr = "001";
        snInt = 1;
    }
    else
    {
        QString sn = QString::number(out_list_code.right(3).toInt() + 1);
        snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
        snInt = snStr.toInt();
    }
    out_list_code = dept_code + QDate::currentDate().toString("yyMMdd") + snStr;

    QSqlRecord rcd;
    QMap<QString, QString> para;
    para["dept_code"] = dept_code;  //库存单位
    para["io_type"] = out_type;   //出库类型
    para["class3_meaning_code"] = class3_meaning_code;   //
    para["receive_dept_code"] = receive_dept_code; //药品接收诊室
    para["in_out"] = "out"; //入，出

    if(ui->cbbMode_c->currentText() == "出库退库" )
    {
        para["state"] = "2";//0 申请， 1审批， 2核准
        //退库进行负数计算
        para["mode"] = "-";
    }
    else
    {
        if(ui->cbbMode_c->currentText() == "报损"
                || ui->cbbMode_c->currentText() == "特殊出库"
                )
        {
            para["state"] = "2";//0 申请， 1审批， 2核准
        }else{
            para["state"] = "1";//0 申请， 1审批， 2核准
        }
        para["mode"] = "";
    }

    pub::db_o.transaction();

    QString tmpSql ;
    QSqlQuery tmpQr ;

    sq = "select * from tmp_pha_input ";
    qrm->exec(sq);
    while(qrm->next())
    {

        serialInt ++ ;//页面内部行号

        if(serialInt > MAX_LINES)
        {
            //每页限制行数
            serialInt = 1;
            snInt ++ ;  //单据号尾号
            QString sn = QString::number(snInt);
            snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
            out_list_code = dept_code + QDate::currentDate().toString("yyMMdd") + snStr;
        }

        para["list_code"] = out_list_code;   //入库单据号
        para["serial_code"] = QString::number(serialInt);   //


        //临时表当前行数据
        rcd = qrm->record();

        tmpSql = "select max(in_list_code) from pha_com_input where in_list_code like '" ;
        tmpSql += receive_dept_code + QDate::currentDate().toString("yyMMdd") + "%'";
        qDebug()<<"获取当前最大出库单据号:"<<tmpSql;

        //生成 out_bill_code
        tmpSql = "SELECT SEQ_PHA_OUTBILL_ID.NEXTVAL FROM DUAL";
        tmpQr = pub::db_o.exec(tmpSql);
        tmpQr.next();
        para["bill_code"] = tmpQr.value(0).toString();

        //保存 pha_com_output
        if(!ins_output(rcd, para))
        {
            pub::db_o.rollback();
            qDebug()<<"pha_com_output 保存失败，数据回滚\n";
            return;
        }

        //保存 pha_com_storage
        if(!ins_storage(rcd, para))
        {
            pub::db_o.rollback();
            qDebug()<<"pha_com_storage 保存失败，数据回滚\n";
            return;
        }

    }


    if(ui->cbbMode_c->currentText() == "出库退库")
    {
        //退库，补齐关联入库记录
        para["in_out"] = "in"; //入，出
        para["dept_code"] = receive_dept_code;  //库存单位
        para["io_type"] = out_type;   //出库类型
        para["receive_dept_code"] = dept_code; //药品接收诊室
        //生成 in_list_code
        QString in_list_code ;

        tmpSql  = "select max(in_list_code) from pha_com_input where in_list_code like '" ;
        tmpSql += receive_dept_code + QDate::currentDate().toString("yyMMdd") + "%'";
        qDebug()<<"获取当前最大入库单据号:"<<tmpSql;

        tmpQr = pub::db_o.exec(tmpSql);
        tmpQr.next();
        in_list_code = tmpQr.value(0).toString();

        QString snStr;
        int snInt, serialInt = 0;
        if(in_list_code.isEmpty())
        {
            snStr = "001";
            snInt = 1;
        }
        else
        {
            QString sn = QString::number(in_list_code.right(3).toInt() + 1);
            snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
            snInt = snStr.toInt();
        }
        in_list_code = receive_dept_code + QDate::currentDate().toString("yyMMdd") + snStr;

        qrm->first();
        serialInt = 0;
        while(true)
        {

            serialInt ++ ;//页面内部行号

            if(serialInt > MAX_LINES)
            {
                //每页限制行数
                serialInt = 1;
                snInt ++ ;  //单据号尾号
                QString sn = QString::number(snInt);
                snStr = QString("000").replace(3 - sn.length(), sn.length(), sn);
                out_list_code = receive_dept_code + QDate::currentDate().toString("yyMMdd") + snStr;
            }

            para["list_code"] = out_list_code;   //入库单据号
            para["serial_code"] = QString::number(serialInt);   //

            //临时表当前行数据
            rcd = qrm->record();

            //出库退库，不生成新 group_code
            para["group_code"] = rcd.value("group_code").toString();

            //生成 in_bill_code
            tmpSql = "SELECT SEQ_PHA_INBILL_ID.NEXTVAL FROM DUAL";
            tmpQr = pub::db_o.exec(tmpSql);
            tmpQr.next();
            para["bill_code"] = tmpQr.value(0).toString();

            //保存 pha_com_input
            if(!ins_input(rcd, para))
            {
                pub::db_o.rollback();
                qDebug()<<"出库退库 pha_com_input 保存失败，数据回滚\n";
                return;
            }

            //保存 pha_com_storage
            if(!ins_storage(rcd, para))
            {
                pub::db_o.rollback();
                qDebug()<<"出库退库 pha_com_storage 保存失败，数据回滚\n";
                return;
            }

            if(!qrm->next())
            {
                break;
            }
        }

    }

    pub::db_o.commit();
    qrm->exec("delete from tmp_pha_input");
    showList();
    change_lock_status("out", true);
    qDebug()<<"出库中间数据转储完成\n";
}

bool Form_yk_rk::ins_output(QSqlRecord rcd, QMap<QString, QString> para)
{
    sq = " INSERT INTO PHA_COM_OUTPUT ( ";
    sq += "DRUG_DEPT_CODE, OUT_BILL_CODE, SERIAL_CODE, GROUP_CODE, ";  // -出库科室编码 -出库单流水号 -序号 -批次号
    sq += "OUT_LIST_CODE, OUT_TYPE, CLASS3_MEANING_CODE, IN_BILL_CODE, ";  // -出库单据号 -出库类型 -出库分类 -入库单号
    sq += "IN_SERIAL_CODE, IN_LIST_CODE, DRUG_CODE, TRADE_NAME, ";  // -入库单序号 -入库单据号 -药品编码 -药品商品名
    sq += "DRUG_TYPE, DRUG_QUALITY, SPECS, PACK_UNIT, PACK_QTY, ";  // -药品类别 -药品性质 -规格 -包装单位 -包装数
    sq += "MIN_UNIT, SHOW_FLAG, SHOW_UNIT, BATCH_NO, MANU_DATE, ";  // -最小单位 -显示的单位标记 -显示的单位 -批号 -生产日期
    sq += "VALID_DATE, PRODUCER_CODE, COMPANY_CODE, RETAIL_PRICE, ";  // -有效期 -生产厂家 -供货单位代码 -零售价
    sq += "WHOLESALE_PRICE, PURCHASE_PRICE, OUT_NUM, SALE_COST, ";  // -批发价 -购入价 -OUT_NUM -零售金额
    sq += "TRADE_COST, APPROVE_COST, STORE_NUM, STORE_COST, ";  // -批发金额 -购入金额 -出库后数量 -出库后金额
    sq += "SPECIAL_FLAG, OUT_STATE, APPLY_NUM, ";  // -特殊标记。1是，0否 -出库状态 0申请、1审批、2核准 -申请出库量
    sq += "APPLY_OPERCODE, APPLY_DATE, EXAM_NUM, EXAM_OPERCODE, ";  // -申请出库人 -申请出库日期 -审批数量 -审批人
    sq += "EXAM_DATE, APPROVE_OPERCODE, APPROVE_DATE, PLACE_CODE, ";  // -审批日期 -核准人 -核准日期 -货位号
    sq += "RETURN_NUM, DRUGED_BILL, MED_ID, DRUG_STORAGE_CODE, ";  // -退库数量 -摆药单号 -制剂序号 -领药单位编码
    sq += "RECIPE_NO, SEQUENCE_NO, GET_PERSON, MARK, OPER_CODE, ";  // -处方号 -处方流水号 -领药人 -备注 -操作员
    sq += "OPER_DATE, ARK_FLAG, ARK_BILL_CODE, OUT_DATE "; //-操作日期 -药柜标志 -药柜号 -出库日期

    sq += " ) values (";

    sq += "'" + para["dept_code"] + "' ,";   //库存科室代码
    sq += para["bill_code"] + " ,";   //出库单流水号
    sq += para["serial_code"] + ","; //-序号
    sq += "'" + rcd.value("group_code").toString() + "' ,";   //批次号
    sq += "'" + para["list_code"] + "' ,";   //出库单据号
    sq += "'" + para["io_type"] + "' ,";   //出库类型
    sq += "'" + para["class3_meaning_code"] + "' ,";   //出库分类
    sq += "0, 0, '', "; //入库单号, 入库单序号, 入库单据号
    sq += "'" + rcd.value("item_code").toString() + "'," ; //-药品编码
    sq += "'" + rcd.value("item_name").toString() + "'," ; //-药品商品名
    sq += "'" + rcd.value("drug_type").toString() + "'," ; //-药品类别
    sq += "'" + rcd.value("drug_quality").toString() + "'," ; //-药品性质
    sq += "'" + rcd.value("specs").toString() + "'," ; //-规格
    sq += "'" + rcd.value("pack_unit").toString() + "'," ; //包装单位
    sq += "'" + rcd.value("pack_qty").toString() + "'," ; //包装数
    sq += "'" + rcd.value("min_unit").toString() + "'," ; //最小单位
    sq += "'0', '', ";//显示的单位标记, 显示的单位
    sq += "'" + rcd.value("batch_no").toString() + "'," ; //批号
    sq += "to_date('" + rcd.value("manu_date").toString() + "','yyyy-mm-dd')," ; //生产日期
    sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd')," ; //有效期
    sq += "'" + rcd.value("fac_code").toString() + "'," ; //生产厂家
    sq += "'" + para["company"] + "'," ; //供货单位代码  ????
    sq += rcd.value("retail_price").toString() + ",0 ," ; //-零售价 -批发价
    sq += rcd.value("purchase_price").toString() + ", " ; //-购入价
    sq += para["mode"] + rcd.value("num").toString() + ", " ; //-数量
    sq += para["mode"] + rcd.value("retail_cost").toString() + ",0 ," ; //-零售金额 -批发金额
    sq += para["mode"] + rcd.value("purchase_cost").toString() + "," ; //-购入金额

    //检索品种库存数量，计算出库后余量，同时检验出库数量是否超过库存数量

    QString tmpSql = "select STORE_SUM,STORE_COST from PHA_COM_STOCKINFO where DRUG_CODE = '"
            + rcd.value("item_code").toString() + "' and DRUG_DEPT_CODE = '" + para["dept_code"] + "' ";
    QString  store_sum, store_cost;
    qDebug()<<"检索品种当前库存数量 ："<<tmpSql;

    QSqlQuery tmpQr = pub::db_o.exec(tmpSql);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "读取 pha_com_stockinfo 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    if(tmpQr.next())
    {
        store_sum = tmpQr.value(0).toString();
        store_cost = tmpQr.value(1).toString();
    }else{
        store_sum = "0";
        store_cost = "0";
    }
    if(para["mode"].isEmpty())
    {
        //正常出库，进行库存数据校验
        if(store_sum.toInt() < rcd.value("num").toInt())
        {
            QMessageBox::warning(this, "注意", "库存数量小于出库数量！" );
            return false;
        }
        sq += "(" + store_sum + ") - (" + rcd.value("num").toString() + ")," ; //出库后库存
        sq += "(" + store_cost + ") - (" + rcd.value("purchase_cost").toString() + ")," ; //出库后金额
    }
    else
    {
        //退库， 进行数量增加
        sq += "(" + store_sum + ") + (" + rcd.value("num").toString() + ")," ; //出库后库存
        sq += "(" + store_cost + ") + (" + rcd.value("purchase_cost").toString() + ")," ; //出库后金额
    }
    sq += "'0','" + para["state"] + "',"; //-特殊标记，1是，0否 -出库状态
    sq += "0, '', to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss') ,"; //-申请出库量, 申请出库人, 申请出库日期
    sq += para["mode"] + rcd.value("num").toString() + ",";  //-审批数量
    sq += "'" + pub::usr_code + "', sysdate, ";  //审批人, 审批日期
    sq += "'', sysdate, '',";//核准人, 核准日期, 货位号
    sq += "0, 0, '',";//退库数量, 摆药单号, 制剂序号
    sq += "'" + para["receive_dept_code"] + "', "; //领药单位编码
    sq += "'', 0, '', "; //处方号, 处方流水号, 领药人
    sq += "'" + para["memo"] + "', "; //备注
    sq += "'" + pub::usr_code + "', sysdate, ";//操作员, 操作日期
    sq += "'0', '0', sysdate ";// ARK_FLAG, ARK_BILL_CODE, out_date

    sq += ")";

    qDebug()<<"插入出库记录 pha_com_output : "<<sq;

    pub::db_o.exec(sq);

    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "插入 pha_com_output 错误！\n" + pub::db_o.lastError().text() );
        return false;
    }

    return true;
}


void Form_yk_rk::on_cbbMode_r_currentTextChanged(const QString &arg1)
{
    if(!initialFinished)
    {
        return;
    }
    if(arg1 == "一般入库" || arg1.indexOf("退库") > 0)
    {
        sq = "select FAC_NAME, FAC_CODE from PHA_COM_COMPANY where COMPANY_TYPE = '1' and VALID_FLAG = '1' order by FAC_NAME";
        qDebug()<<"提取一般入库目标："<<sq;
        company_code = pub::fillCombo(ui->cbbCompany, sq, -1, qrot);
    }
    else if(arg1 == "核准入库" || arg1 == "特殊入库" )
    {
        sq  = "select dept_name,dept_code from com_department where "
              " valid_state = '1' and dept_type in ('P','PI') order by dept_type,dept_name";//,'N' ,护士站
        qDebug()<<"提取核准入库目标："<<sq;
        company_code = pub::fillCombo(ui->cbbCompany, sq, -1, qrot);
    }
    else
    {
        ui->cbbCompany->clear();
    }
}

void Form_yk_rk::on_cbbReceiveDept_currentIndexChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    if(!initialFinished)
    {
        return;
    }

    qrm->exec("delete from tmp_pha_input");
    showList();
}

void Form_yk_rk::on_leRksl_2_returnPressed()
{
    if(ui->leRksl_2->text().isEmpty())
    {
        return;
    }
    ui->pbAdd_2->setFocus();
}

void Form_yk_rk::on_leRksl_returnPressed()
{

    if(ui->leRksl->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leFph->setFocus();
    }

}

QRectF Form_yk_rk::getRealPosition(int row, int col)
{

    float x1,x2,y1,y2;
    if(col > 0)
    {
        //单个单元格
        x1 = (grid_col[ col - 1 ].toDouble() + margin + xPos) * ptScale;
        x2 = (grid_col[ col ].toDouble() - margin + xPos) * ptScale;
    }
    else
    {
        //合并单元格
        int col1,col2;
        col1 = (0 - col) / 100;
        col2 = (0 - col) % 100;
        x1 = (grid_col[ col1 - 1 ].toDouble() + margin + xPos) * ptScale;
        x2 = (grid_col[ col2 ].toDouble() - margin + xPos) * ptScale;
    }
    if(row > 0 )
    {
        y1 = (grid_row[ row - 1 ].toDouble() + yPos) * ptScale;
        y2 = (grid_row[ row ].toDouble() + yPos) * ptScale;
    }
    else
    {
        int row1,row2;
        row1 = (0 - row) / 100;
        row2 = (0 - row) % 100;
        y1 = (grid_row[ row1 - 1 ].toDouble() + yPos) * ptScale;
        y2 = (grid_row[ row2 ].toDouble() + yPos) * ptScale;
    }
    QPointF p1 = QPointF(x1, y1);
    QPointF p2 = QPointF(x2, y2);
//qDebug()<<"get real position : "<<QString::number(row)<<","<<QString::number(col)<<","<<p1<<","<<p2;
    return QRectF(p1 , p2);

}

void Form_yk_rk::printCellItem(QString item_name, QString item_value, int pos)
{
    sq = "select p_type,p_item,p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
         " p_position,p_mode,p_print_item,p_item_type from com_printer_setting "
         " where p_type = '入出库单' and p_item_type = 'item'"
         " and p_item = '" + item_name + "'";
    qrmp->exec(sq);

    if(!qrmp->next())
    {
        QMessageBox::information(this, "注意", "项目名称 " + item_name + " 不存在 ！");
        return;
    }

    QFont ft;
    ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
    ft.setFamily(qrmp->value("p_font_name").toString());
    pnt->setFont(ft);

    int flag;
    if(qrmp->value("p_position").toInt() == 0){ //左
        flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
    }else if(qrmp->value("p_position").toInt() == 1){//中
        flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
    }else{          //右
        flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
    }

    QRectF f; //打印范围区域

    if( qrmp->value("p_width").toInt() == 0
            && qrmp->value("p_height").toInt() == 0)
    {
        //以表格为参照，需要进行换算
        f = getRealPosition(qrmp->value("p_top").toInt() + pos , qrmp->value("p_left").toInt());
    }
    else
    {
        f = QRectF((qrmp->value("p_left").toDouble() + xPos) * ptScale,
                   (qrmp->value("p_top").toDouble() + yPos) * ptScale,
                   (qrmp->value("p_width").toDouble())  * ptScale,
                   (qrmp->value("p_height").toDouble()) * ptScale);
    }

    pnt->drawText(f, flag, item_value, NULL);

}

void Form_yk_rk::printPageBase()
{

    //表格线
    double x1, y1, x2, y2, width ;
    QPen p ;
    p.setStyle(Qt::SolidLine);

    sq = "select p_type,p_item,p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
         "p_position,p_mode,p_print_item,p_item_type from com_printer_setting "
         "where p_type = '入出库单' and p_item_type = 'base'";
    qrmp->exec(sq);
    while(qrmp->next())
    {
        if(qrmp->value("p_item").toString() == "grid_col")
        {
            grid_col = qrmp->value("p_print_item").toString().split("^");
        }
        else if(qrmp->value("p_item").toString() == "grid_row")
        {
            grid_row = qrmp->value("p_print_item").toString().split("^");
        }
    }

    qrmp->first();
    while(true)
    {
        if( qrmp->value("p_item").toString() == "line_landscape")
        {
            width = qrmp->value("p_font_size").toDouble();
            x1 = (qrmp->value("p_top").toDouble() + xPos) * ptScale;
            y1 = (qrmp->value("p_left").toDouble() + yPos) * ptScale;
            x2 = (qrmp->value("p_width").toDouble() + xPos) * ptScale;
            y2 = (qrmp->value("p_height").toDouble() + yPos) * ptScale;

            p.setWidth( ptScale * width);
            pnt->setPen(p);
            pnt->drawLine(x1, y1, x2, y2);

            QStringList stepList = qrmp->value("p_print_item").toString().split("^");

            for(int i = 0; i < stepList.size(); i++)
            {
                y1 = (stepList[i].toDouble() + yPos) * ptScale ;
                y2 = (stepList[i].toDouble() + yPos) * ptScale ;
                pnt->drawLine(x1, y1, x2, y2);
            }

        }
        else if( qrmp->value("p_item").toString() == "line_portrait")
        {
            width = qrmp->value("p_font_size").toDouble();
            x1 = (qrmp->value("p_top").toDouble() + xPos) * ptScale;
            y1 = (qrmp->value("p_left").toDouble() + yPos) * ptScale;
            x2 = (qrmp->value("p_width").toDouble() + xPos) * ptScale;
            y2 = (qrmp->value("p_height").toDouble() + yPos) * ptScale;

            p.setWidth( ptScale * width);
            pnt->setPen(p);
            pnt->drawLine(x1, y1, x2, y2);
            //QString step = qrmp->value("p_item").toString();
            QStringList stepList = qrmp->value("p_print_item").toString().split("^");

            for(int i = 0; i < stepList.size(); i++)
            {
                x1 = (stepList[i].toDouble() + xPos) * ptScale ;
                x2 = (stepList[i].toDouble() + xPos) * ptScale ;
                pnt->drawLine(x1, y1, x2, y2);
            }

        }
        else if( qrmp->value("p_item").toString() == "solid")
        {
            QFont ft;
            ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
            ft.setFamily(qrmp->value("p_font_name").toString());
            pnt->setFont(ft);

            int flag;
            if(qrmp->value("p_position").toInt() == 0){ //左
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
            }else if(qrmp->value("p_position").toInt() == 1){//中
                flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
            }else{          //右
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
            }

            QString txt = qrmp->value("p_print_item").toString();

            QRectF f; //打印范围区域

            if( qrmp->value("p_width").toInt() == 0
                    && qrmp->value("p_height").toInt() == 0)
            {
                //以表格为参照，需要进行换算
                f = getRealPosition(qrmp->value("p_top").toInt(), qrmp->value("p_left").toInt());
            }
            else
            {
                f = QRectF((qrmp->value("p_left").toDouble() + xPos) * ptScale,
                           (qrmp->value("p_top").toDouble() + yPos) * ptScale,
                           (qrmp->value("p_width").toDouble())  * ptScale,
                           (qrmp->value("p_height").toDouble()) * ptScale);
            }

            pnt->drawText(f, flag, txt, NULL);
        }
        if(!qrmp->next())
        {
            break;
        }
    }
}

void Form_yk_rk::on_pbPrintOut_clicked()
{
    if(ui->lwToPrint->count() == 0)
    {
        QMessageBox::warning(this, "注意", "未选定打印的出入库单！");
        return ;
    }

    QString io, io_list_code;
    QMap<QString, QString> printItem;

    for(int i = 0; i < ui->lwToPrint->count() ; i++)
    {
        printItem.clear();

        io = pub::getStr(ui->lwToPrint->item(i)->text(), "^", 1);
        io_list_code = pub::getStr( ui->lwToPrint->item(i)->text(), "^", 2);

        qDebug()<<"io_list_code is : "<<io<<","<<io_list_code;

        if(io == "入库单")
        {
            sq = "select drug_dept_code, in_list_code 单据号,in_type, drug_code 药品编码, "
                 " trade_name 药品名称, specs 规格, in_num / pack_qty 数量, pack_unit 单位, "
                 " purchase_price 购入价, purchase_cost 购入金额, retail_price 销售价, retail_cost 销售金额,"
                 " retail_cost - purchase_cost 差价, mark, batch_no 批号, "
                 " to_char(valid_date, 'yyyy-mm-dd') 效期, company_code , "
                 " to_char(in_date, 'yyyy-mm-dd') in_date "
                 " from pha_com_input"
                 " where in_num <> 0 and in_list_code = '" + io_list_code +"' order by serial_code";
        }
        else
        {
            sq = "select drug_dept_code, out_list_code 单据号,out_type, drug_code 药品编码, "
                 " trade_name 药品名称, specs 规格, out_num / pack_qty 数量, pack_unit 单位, "
                 " purchase_price 购入价, approve_cost 购入金额, retail_price 销售价, sale_cost 销售金额,"
                 " sale_cost - approve_cost 差价,  mark, batch_no 批号, "
                 " to_char(valid_date, 'yyyy-mm-dd') 效期, drug_storage_code company_code , "
                 " to_char(out_date, 'yyyy-mm-dd') out_date "
                 " from pha_com_output"
                 " where out_num <> 0 and out_list_code = '" + io_list_code +"' order by serial_code";
        }

qDebug()<<" prepare to print: "<<sq;
        qro->exec(sq);
        qro->next();

        printItem["库房"] = "库房：" + ui->cbbStoreDept->currentText();
        printItem["单据号"] = "单据号：" + io_list_code;

        if(io == "入库单")
        {
            sq = "select fac_name from pha_com_company where fac_code = '"
                    + qro->value("company_code").toString() + "' ";
            qrot->exec(sq);
            qrot->next();
            printItem["目标单位"] = "供货商：" + qrot->value(0).toString() ;
            printItem["出入日期"] = "入库日期：" + qro->value("in_date").toString() ;
            sq = "select class3_name from com_priv_class3 where class3_code = '"
                    + qro->value("in_type").toString() + "' and class2_code = '0310'";

        }
        else
        {
            //出库单
            sq = "select dept_name from com_department where valid_state = '1' and dept_code = '"
                    + qro->value("company_code").toString() + "' ";
            qrot->exec(sq);
            qrot->next();
            printItem["目标单位"] = "出库去向：" + qrot->value(0).toString() ;
            printItem["出入日期"] = "出库日期：" + qro->value("out_date").toString() ;
            sq = "select class3_name from com_priv_class3 where class3_code = '"
                    + qro->value("out_type").toString() + "' and class2_code = '0320'";

        }
        qrot->exec(sq);
        qrot->next();
        printItem["标题"] = ui->cbbStoreDept->currentText() + io + "(" + qrot->value(0).toString() + ")";

        printItem["保管员"] = "保管员:";
        printItem["操作员"] = "操作员:" + pub::usr_name;
        printItem["打印日期"] = "打印日期：" + QDateTime::currentDateTime().toString("yyyy-MM-dd");

        pnt->begin(prt);
        printPageBase();
        QMap<QString, QString>::iterator itor;
        for(itor = printItem.begin(); itor != printItem.end(); itor++)
        {
            printCellItem(itor.key(), itor.value(), 0 );
            qDebug()<<itor.key()<<","<< itor.value();
        }

        double all_cost_in = 0;    //单据购入金额
        double all_cost_out = 0;    //单据销价金额
        double all_cost_diff = 0;    //差价
        QString batch_valid = "药品编码,批号,效期 : \n";    //药品编码 ，批号，效期
        QString mark = "备注 : ";    //备注
        int lines = 0;  //单据内行序数
        printItem.clear();
        while(true)
        {
            //printItem["药品编码"] = qro->value("药品编码").toString();
            printItem["药品名称"] = qro->value("药品名称").toString();
            printItem["规格"] = qro->value("规格").toString();
            printItem["数量"] = qro->value("数量").toString();
            printItem["单位"] = qro->value("单位").toString();
            printItem["购入价"] = QString::number(qro->value("购入价").toDouble(),'f',2) ;
            printItem["购入金额"] = QString::number(qro->value("购入金额").toDouble(),'f',2) ;
            printItem["销售价"] = QString::number(qro->value("销售价").toDouble(),'f',2) ;
            printItem["销售金额"] = QString::number(qro->value("销售金额").toDouble(),'f',2) ;
            printItem["差价"] = QString::number(qro->value("差价").toDouble(),'f',2) ;

            for(itor = printItem.begin(); itor != printItem.end(); itor++)
            {
                printCellItem(itor.key(), itor.value(), lines );
            }

            all_cost_in += qro->value("购入金额").toDouble();
            all_cost_out += qro->value("销售金额").toDouble();
            all_cost_diff += qro->value("差价").toDouble();
            batch_valid += qro->value("药品编码").toString() + ", " + qro->value("批号").toString() + ", " +qro->value("效期").toString() + "; ";
            if(!qro->value("mark").toString().isEmpty())
            {
                mark += qro->value("药品名称").toString() + ": " + qro->value("mark").toString() + ";";
            }

            if(!qro->next())
            {
                break;
            }
            lines ++;
        }

        printCellItem("合计入", QString::number(all_cost_in, 'f', 2), 0 );
        printCellItem("合计销", QString::number(all_cost_out, 'f', 2), 0 );
        printCellItem("合计差", QString::number(all_cost_diff, 'f', 2), 0 );
        QString bat_mark = batch_valid;
        if(mark != "备注 : ")
        {
            bat_mark += "\n" + mark;
        }

        printCellItem("备注", bat_mark, 0 );

        pnt->end();
    }

    if(ui->ckb_clear_after_print->isChecked())
    {
        ui->lwToPrint->clear();
    }

}

void Form_yk_rk::on_prPrintSearch_clicked()
{
    if(ui->cbbStoreDept->currentText().isEmpty())
    {
        QMessageBox::warning(this, "注意", "未指定当前工作库房！");
        return ;
    }
    QString begin = ui->deBegin->date().toString("yyyy-MM-dd");
    QString end = ui->deEnd->date().toString("yyyy-MM-dd");
    QString dateRangeIn = " and trunc(in_date) >= to_date('" + begin + "','yyyy-mm-dd') ";
    dateRangeIn += " and trunc(in_date) <= to_date('" + end + "','yyyy-mm-dd') ";
    QString dateRangeOut = " and trunc(out_date) >= to_date('" + begin + "','yyyy-mm-dd') ";
    dateRangeOut += " and trunc(out_date) <= to_date('" + end + "','yyyy-mm-dd') ";

    //检索科室代码
    int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    sq = "select distinct dept.dept_name 库房名称, input.in_list_code 入库单号, priv.class3_name 入库类别"
         " from pha_com_input input ";
    sq += " left join com_department dept on input.drug_dept_code = dept.dept_code ";
    sq += " left join com_priv_class3 priv on priv.class3_code = input.in_type and priv.class2_code = '0310'";
    sq += " where input.drug_dept_code = '" + dept_code + "' " +  dateRangeIn;
    sq += " order by input.in_list_code desc";
    qDebug()<<"search in list : "<<sq;
    md_p_in->setQuery(sq, pub::db_o);
    ui->tvInList->setModel(md_p_in);
    int width = ui->tvInList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvInList, "0.3^0.3^0.3", width, 10);

    sq = "select distinct dept.dept_name 库房名称, output.out_list_code 出库单号, priv.class3_name 出库类别"
         " from pha_com_output output ";
    sq += " left join com_department dept on output.drug_dept_code = dept.dept_code ";
    sq += " left join com_priv_class3 priv on priv.class3_code = output.out_type and priv.class2_code = '0320'";
    sq += " where output.drug_dept_code = '" + dept_code + "' and out_list_code is not null " +  dateRangeOut;
    sq += " order by out_list_code desc";
    qDebug()<<"search out list : "<<sq;
    md_p_out->setQuery(sq, pub::db_o);
    ui->tvOutList->setModel(md_p_out);
    width = ui->tvOutList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvOutList, "0.3^0.3^0.3", width, 10);

}

void Form_yk_rk::on_tvInList_clicked(const QModelIndex &index)
{
    sq = "select drug_dept_code, in_list_code 单据号,in_type, drug_code 药品编码, "
         " trade_name 药品名称, specs 规格, in_num / pack_qty 数量, pack_unit 单位, "
         " purchase_price 价格, purchase_cost 金额, mark, batch_no 批号, "
         " to_char(valid_date, 'yyyy-mm-dd') 效期 "
         " from pha_com_input"
         " where in_num <> 0 and in_list_code = '"
         + index.siblingAtColumn(1).data().toString() +"'order by serial_code";

    listPrintItem(sq);
}

void Form_yk_rk::listPrintItem(QString sq)
{
    //根据 list code 显示单据内容
    qDebug()<<"display items : "<<sq;
    md_p_brw->setQuery(sq, pub::db_o);
    ui->tvBrowse->setModel(md_p_brw);

    pub::setColumnWidth(ui->tvBrowse, "0^0.1^0^0.1^0.2^0.1^0.08^0.04^0.08^0.08^0^0.08^0.08", ui->tvBrowse->horizontalHeader()->width() , 20);
}

void Form_yk_rk::on_tvInList_doubleClicked(const QModelIndex &index)
{
    QString itm = "入库单^";
    itm += index.siblingAtColumn(1).data().toString();
    QList<QListWidgetItem*> found = ui->lwToPrint->findItems(itm, Qt::MatchExactly);
    if(found.size() == 0)
    {
        ui->lwToPrint->addItem(itm);
    }
}

void Form_yk_rk::on_tvOutList_clicked(const QModelIndex &index)
{
    sq = "select drug_dept_code, out_list_code 单据号,out_type, drug_code 药品编码, "
         " trade_name 药品名称, specs 规格, out_num / pack_qty 数量, pack_unit 单位, "
         " purchase_price 价格, sale_cost 金额, mark, batch_no 批号, "
         " to_char(valid_date, 'yyyy-mm-dd') 效期 "
         " from pha_com_output"
         " where out_num <> 0 and out_list_code = '"
         + index.siblingAtColumn(1).data().toString() +"'order by serial_code";

    listPrintItem(sq);
}

void Form_yk_rk::on_tvOutList_doubleClicked(const QModelIndex &index)
{
    QString itm = "出库单^";
    itm += index.siblingAtColumn(1).data().toString();
    QList<QListWidgetItem*> found = ui->lwToPrint->findItems(itm, Qt::MatchExactly);
    if(found.size() == 0)
    {
        ui->lwToPrint->addItem(itm);
    }

}

void Form_yk_rk::on_lwToPrint_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)
    ui->lwToPrint->takeItem(ui->lwToPrint->currentRow());
}

void Form_yk_rk::on_leFph_returnPressed()
{
    if(ui->leFph->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->leFprq->setFocus();
        ui->leFprq->selectAll();
    }
}

void Form_yk_rk::on_leFprq_returnPressed()
{
    ui->pbAdd->setFocus();
}

void Form_yk_rk::on_leTax_textChanged(const QString &arg1)
{
    Q_UNUSED(arg1)

    calc_amount();
}

void Form_yk_rk::on_tvDest_r_clicked(const QModelIndex &index)
{
    QString item_code = index.siblingAtColumn(6).data().toString();
    item_detail.insert("item_name_0", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs_0", index.siblingAtColumn(1).data().toString());   //规格

    sq = "select * from tmp_pha_input where item_code = '" + item_code + "'";
    qrm->exec(sq);
    qrm->next();

    ui->lePzwh->setText(qrm->value("approve_info").toString());
    ui->leScs->setText(qrm->value("fac_name").toString());
    ui->leLsjg->setText(qrm->value("retail_price").toString());;
    ui->lePackQty->setText(qrm->value("pack_qty").toString());
    ui->lePackUnit->setText(qrm->value("pack_unit").toString());
    ui->leGrjg->setText(qrm->value("purchase_price").toString());

    ui->lePh->setText(qrm->value("batch_no").toString());
    ui->leScrq->setText(qrm->value("manu_date").toString());
    ui->leXq->setText(qrm->value("valid_date").toString());
    ui->leRksl->setText(QString::number(qrm->value("num").toInt() / qrm->value("pack_qty").toInt()));

    ui->leFph->setText(qrm->value("invo_no").toString());
    ui->leFprq->setText(qrm->value("invo_date").toString());

}

void Form_yk_rk::on_tvDest_r_doubleClicked(const QModelIndex &index)
{
    on_tvDest_r_clicked(index);
}

void Form_yk_rk::change_lock_status(QString type, bool status)
{
    //设置状态锁定或解除
    if(type == "in")
    {
        ui->cbbStoreDept->setEnabled(status);
        ui->cbbMode_r->setEnabled(status);
        ui->cbbCompany->setEnabled(status);

        if(status)
        {
            ui->pb_status_unlock_in->setEnabled(false);
            mdrs->setQuery(NULL);
        }
        else
        {
            ui->pb_status_unlock_in->setEnabled(true);

        }

    }
    else if(type == "out")
    {
        ui->cbbStoreDept->setEnabled(status);
        ui->cbbMode_c->setEnabled(status);
        ui->cbbReceiveDept->setEnabled(status);
        if(status)
        {
            ui->pb_unlock_status_out->setEnabled(false);
            mdcs->setQuery(NULL);
        }
        else
        {
            ui->pb_unlock_status_out->setEnabled(true);

        }
    }
}
void Form_yk_rk::on_pb_status_unlock_in_clicked()
{
    if(mdrd->rowCount()>0)
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "录入项目数据未保存，是否清除然后继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        mdrd->setQuery(NULL);
        qrm->exec("delete from tmp_pha_input");
    }
    change_lock_status("in", true);
}

void Form_yk_rk::on_pb_unlock_status_out_clicked()
{
    if(mdcd->rowCount()>0)
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "录入项目数据未保存，是否清除然后继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        mdcd->setQuery(NULL);
        qrm->exec("delete from tmp_pha_input");
    }
    change_lock_status("out", true);
}

void Form_yk_rk::search_checked(QString sour, QString dest)
{

    //可以自动录入的内容
    if(ui->cbbMode_r->currentText() == "一般入库")
    {
        //从入库验收表提取内容
        from_input_check(sour, dest);
    }
    else if(ui->cbbMode_r->currentText() == "核准入库")
    {
        //从上级库出库表提取内容
        from_other_store(sour, dest);
    }

    showList();

}

void Form_yk_rk::from_input_check(QString sour, QString dest)
{

    sq = "select * from pha_com_input_check"
         " where drug_dept_code = '%1' and in_state = '0' "
         " and company_code = '%2' and valid_flag = '1' and check_result = '1'";
    sq = sq.arg(dest).arg(sour);

    qDebug()<<"检索已经验收的入库记录："<<sq<<"\n";
    qro->exec(sq);
    if(!qro->next())
    {
        QMessageBox::information(this, "注意", "找不到指定条件的验收记录！");
        return;
    }

    while(true)
    {
        //入库数据插入临时表

        sq = "replace into tmp_pha_input ("
             "item_code, item_name, fac_code, fac_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
        sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
        sq += "drug_quality, retail_price, purchase_price,";   //药品普药特药类别，零售价格,采购价格
        sq += "med_list_codg,"; //医保码
        sq += "batch_no, manu_date, valid_date, num,";   //批号,生产日期,效期,数量
        sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
        sq += "out_bill_code, out_list_code, out_serial_code, input_check_no, group_code";//
        sq += ") values(";
        sq += "'" + qro->value("drug_code").toString() + "',";//药品编码
        sq += "'" + qro->value("trade_name").toString() + "',";//品名
        sq += "'" + qro->value("producer_code").toString() + "',";//生产商

        qrot->exec("select fac_name from pha_com_company "
                   " where fac_code = '"
                   + qro->value("producer_code").toString()
                   + "' and company_type = '0'");
        qrot->next();
        sq += "'" + qrot->value("fac_name").toString() + "',";//生产商"

        sq += "'" + qro->value("specs").toString() + "',";//规格
        sq += "'" + qro->value("approve_no").toString() + "',";//批准文号
        sq += "'" + qro->value("pack_qty").toString() + "',";//包装数量
        sq += "'" + qro->value("pack_unit").toString() + "',";//包装单位
        sq += "'" + qro->value("drug_type").toString() + "',";//药品类别，中药，西药
        sq += "'" + qro->value("drug_quality").toString() + "',";//药品类别，普药，特药
        sq += "'" + qro->value("retail_price").toString() + "',";//零售价格
        sq += "'" + qro->value("purchase_price").toString() + "',";//采购价格
        sq += "'" + qro->value("med_list_codg").toString() + "',";//医保码
        sq += "'" + qro->value("batch_no").toString() + "',";//批号
        sq += "'" + qro->value("manu_date").toDate().toString("yyyy-MM-dd") + "',";//生产日期
        sq += "'" + qro->value("valid_date").toDate().toString("yyyy-MM-dd") + "',";//效期
        //sq += QString::number(qro->value("apply_num").toInt() *  qro->value("pack_qty").toInt()) + ",";//数量
        sq += "'" + qro->value("apply_num").toString() + "',";//数量
        sq += "'',";//发票号" + ui->leFph->text().trimmed() + "
        sq += "'0001-01-01',";//发票日期" + ui->leFprq->text().trimmed() + "
        sq += "'" + qro->value("mark").toString() + "',";//备注
        sq += "'" + qro->value("min_unit").toString() + "',";//" + item_detail["min_unit"] + "
        sq += qro->value("apply_num").toString() +
                "*" + qro->value("purchase_price").toString() +
                "/" + qro->value("pack_qty").toString()+ ",";//购入金额
        sq += qro->value("apply_num").toString() +
                "*" + qro->value("retail_price").toString() +
                "/" + qro->value("pack_qty").toString()+ ",";//零售金额
        sq += "'0',";//
        sq += "'',";//
        sq += "'0',";//
        sq += "'" + qro->value("input_check_no").toString() + "',";//验收记录流水号
        sq += "'0'";//
        sq += ")";

        qDebug()<<"insert data to temporary table : "<< sq;

        if(!qrm->exec(sq))
        {
            QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
            return ;
        }

        if(!qro->next())
        {
            break;
        }
    }
}

void Form_yk_rk::from_other_store(QString sour, QString dest)
{

    sq = " select T.TRADE_NAME , T.SPECS , F.fac_name , S.APPROVE_INFO, " //0 - 3
         " T.PACK_QTY, T.PACK_UNIT, T.DRUG_TYPE, T.DRUG_QUALITY, T.RETAIL_PRICE, T.PURCHASE_PRICE," //4 - 9
         " T.DRUG_CODE , T.PRODUCER_CODE , T.min_unit, c.med_list_codg, ";//10 - 13
    sq += " T.batch_no , T.manu_date, T.valid_date, T.PURCHASE_PRICE, "//14 - 17
          "T.group_code, T.OUT_NUM - T.RETURN_NUM apply_num,"; //18 - 19
    sq += " T.OUT_BILL_CODE, T.OUT_LIST_CODE, T.SERIAL_CODE";//20 - 22
    sq += " FROM PHA_COM_OUTPUT T ";
    sq += " left join PHA_COM_BASEINFO S on S.DRUG_CODE = T.DRUG_CODE ";
    sq += " left join PHA_COM_COMPANY F on F.FAC_CODE = T.PRODUCER_CODE ";
    sq += " left join fin_com_compare c on c.FIXMEDINS_HILIST_ID = t.DRUG_CODE ";
    sq += " where T.OUT_STATE = '1'";
    sq += " AND T.DRUG_STORAGE_CODE = '" + dest + "'";
    sq += " AND T.DRUG_DEPT_CODE = '" + sour + "' ";
    sq += " AND T.OUT_NUM - T.RETURN_NUM > 0";
    //sq += " and (S.SPELL_CODE like '%" + key.toUpper() + "%' or S.TRADE_NAME like '%" + key + "%' )";
    //sq += " order by S.TRADE_NAME";
    //sq = sq.arg(dest).arg(sour);

    qDebug()<<"检索需要核准入库的记录："<<sq<<"\n";
    qro->exec(sq);
    if(!qro->next())
    {
        QMessageBox::information(this, "注意", "找不到需要核准的入库记录！");
        return;
    }

    while(true)
    {
        //入库数据插入临时表

        sq = "replace into tmp_pha_input ("
             "item_code, item_name, fac_code, fac_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
        sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
        sq += "drug_quality, retail_price, purchase_price,";   //药品普药特药类别，零售价格,采购价格
        sq += "med_list_codg,"; //医保码
        sq += "batch_no, manu_date, valid_date, num,";   //批号,生产日期,效期,数量
        sq += "invo_no, invo_date, memo, min_unit, purchase_cost,retail_cost ,";   //发票号, 发票日期, 备注， 购入金额，零售金额
        sq += "out_bill_code, out_list_code, out_serial_code, group_code";//
        sq += ") values(";
        sq += "'" + qro->value("drug_code").toString() + "',";//药品编码
        sq += "'" + qro->value("trade_name").toString() + "',";//品名
        sq += "'" + qro->value("producer_code").toString() + "',";//生产商
        sq += "'" + qro->value("fac_name").toString() + "',";//生产商"
        sq += "'" + qro->value("specs").toString() + "',";//规格
        sq += "'" + qro->value("approve_info").toString() + "',";//批准文号
        sq += "'" + qro->value("pack_qty").toString() + "',";//包装数量
        sq += "'" + qro->value("pack_unit").toString() + "',";//包装单位
        sq += "'" + qro->value("drug_type").toString() + "',";//药品类别，中药，西药
        sq += "'" + qro->value("drug_quality").toString() + "',";//药品类别，普药，特药
        sq += "'" + qro->value("retail_price").toString() + "',";//零售价格
        sq += "'" + qro->value("purchase_price").toString() + "',";//采购价格
        sq += "'" + qro->value("med_list_codg").toString() + "',";//医保码
        sq += "'" + qro->value("batch_no").toString() + "',";//批号
        sq += "'" + qro->value("manu_date").toDate().toString("yyyy-MM-dd") + "',";//生产日期
        sq += "'" + qro->value("valid_date").toDate().toString("yyyy-MM-dd") + "',";//效期
        sq += QString::number(qro->value("apply_num").toInt())+ ",";//数量/ qro->value("pack_qty").toInt()) + ",";//数量
        sq += "'',";//发票号" + ui->leFph->text().trimmed() + "
        sq += "'0001-01-01',";//发票日期" + ui->leFprq->text().trimmed() + "
        sq += "'',";//备注" + qro->value("mark").toString() + "
        sq += "'" + qro->value("min_unit").toString() + "',";//" + item_detail["min_unit"] + "
        sq += qro->value("apply_num").toString()
                + "/" + qro->value("pack_qty").toString()
                + "*" + qro->value("purchase_price").toString()+",";//购入金额
        sq += qro->value("apply_num").toString()
                + "/" + qro->value("pack_qty").toString()
                + "*" + qro->value("retail_price").toString()+",";//零售金额
        sq += "'" + qro->value("OUT_BILL_CODE").toString() + "',";//,
        sq += "'" + qro->value("OUT_LIST_CODE").toString() + "',";//
        sq += "'" + qro->value("SERIAL_CODE").toString() + "',";//
        sq += "'" + qro->value("group_code").toString() + "'";//
        sq += ")";

        qDebug()<<"insert data to temporary table : "<< sq;

        if(!qrm->exec(sq))
        {
            QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
            return ;
        }

        if(!qro->next())
        {
            break;
        }
    }
}

QString Form_yk_rk::get_input_check_no()
{

    //检索科室代码
    int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
    QString dept = pub::getStr(store_depts, "^", pos);

    //检索代货商代码
    pos = pub::searchStr(company_code, "^", ui->cbbCompany->currentText()) + 1;
    QString company = pub::getStr(company_code, "^", pos);

    sq = " select input_check_no "
         " from pha_com_input_check"
         " where drug_dept_code = '%1' and in_state = '0' "
         " and apply_date > sysdate - 15 and drug_code = '%2' "
         " and batch_no = '%3' and apply_num = '%4' and company_code = '%5'";
    sq = sq.arg(dept)
            .arg(item_detail["item_code"])
            .arg(ui->lePh->text().trimmed())
            .arg(QString::number(ui->leRksl->text().toInt() *
                                 ui->lePackQty->text().toInt()))
            .arg(company);
    qDebug()<<"根据录入内容匹配验收记录："<<sq<<"\n";
    qro->exec(sq);
    if(qro->next())
    {
        return qro->value(0).toString();
    }
    else
    {
        return "";
    }

}
